• 横向滚动菜单-选中标题居中显示


    很多时候我们都会遇到这种需求,在移动端端显示导航栏横向内滚动,可以左右滑动,同时将选中的目标元素居中显示。那我们该如何去实现呢,不管是APP,移动端段网页还是小程序,其原理都是相同的,接下来我就拿小程序举个例子,先画个图解释下:

    具体步骤:

    1.获取当前设备的宽度

     onShow: function () {
        // 获取当前设备的宽度
        this.setData({
          deviceWidth: wx.getSystemInfoSync().windowWidth
        })
      },

    2.获取当前元素的宽度以及距离父元素左边的距离offsetleft

      onMove:function(e){
        // 创建节点
        var query = wx.createSelectorQuery();
        //选择id
        var that = this;
        var width = 0
        // 获取当前点击元素的宽度
        query.select('#item_' + e.currentTarget.dataset.index).boundingClientRect(function (rect) {
          width = rect.width;
          // 激活当前选中项
          that.data.tabmenu.forEach(function (element, index) {
            element.active = false
            if (e.currentTarget.dataset.index == index) {
              element.active = true
            }
          })
          that.setData({
            tabmenu: that.data.tabmenu,
            // 设置选中元素居中显示
            scrollLeft: e.currentTarget.offsetLeft + (width / 2 - that.data.deviceWidth / 2)
          })
        }).exec();
        
      },

    3.设置选中元素居中

    JS:

    scrollLeft: e.currentTarget.offsetLeft + (width / 2 - that.data.deviceWidth / 2)

    wxml:

    <!-- 标题栏 -->
          <scroll-view class="scroll-view_H" id="scroll-view_H" bindscroll="onScroll" scroll-left="{{scrollLeft}}" scroll-with-animation scroll-x="true">
            <block wx:for="{{tabmenu}}" wx:key="{{index}}">
              <view class="scroll-view-item_H {{item.active?'active':''}} " id="item_{{index}}" data-index="{{index}}" bindtap='onMove'>{{item.name}}</view>
            </block>
          </scroll-view>

    data数据

        tabmenu:[{
          name: 'Html',
          active: true
        }, {
          name: 'CSS',
          active: false
        }, {
          name: 'Javascript',
          active: false
        }, {
          name: 'Es6',
          active: false
        }, {
          name: 'Vue',
          active: false
        }]

    效果图如下:

    当你微笑的时候,全世界都会对你微笑。
  • 相关阅读:
    NTP时钟服务器(卫星授时)技术让网络时间同步不再难
    视频监控系统为何需要GPS北斗授时服务器?
    如何选购GPS北斗卫星时钟同步装置?市场均价多少?
    Orange'S学习笔记(一)
    Oracle 11g中文版高清视频教程
    新书推荐:Orange'S:一个操作系统的实现
    引导扇区汇编代码解释
    灰度图转伪彩色图代码
    Visual Odometry For GPSDenied Flight And Mapping Using A Kinect
    [原创]日行一善,命运在不知不觉中改变
  • 原文地址:https://www.cnblogs.com/liruoruo/p/10172350.html
Copyright © 2020-2023  润新知