zoukankan      html  css  js  c++  java
  • 横向滚动菜单-选中标题居中显示

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

    效果图如下:

    当你微笑的时候,全世界都会对你微笑。
  • 相关阅读:
    程序的链接
    Graphviz 画图的一些总结
    C表达式中的汇编指令
    epoll(2) 源码分析
    epoll(2) 使用及源码分析的引子
    eventfd(2) 结合 select(2) 源码分析
    poll(2) 源码分析
    select 源码分析
    kfifo
    程序的机器级表示:寻址方式、指令及栈的运行机制
  • 原文地址:https://www.cnblogs.com/liruoruo/p/10172350.html
Copyright © 2011-2022 走看看