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

很多时候我们都会遇到这种需求,在移动端端显示导航栏横向内滚动,可以左右滑动,同时将选中的目标元素居中显示。那我们该如何去实现呢,不管是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
    }]

效果图如下:

 

转载于:https://www.cnblogs.com/liruoruo/p/10172350.html

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值