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
        }]

    效果图如下:

    当你微笑的时候,全世界都会对你微笑。
  • 相关阅读:
    Nginx进阶-不停服更新
    Tengine安装
    初识Nginx
    自建Nuget服务器
    WebApi PUT、DELETE请求时出现405
    Mysql分页查询性能分析
    Asp.Net WebApi Swagger终极搭建
    到底什么是程序员思维,设计师思维
    [有了SSL证书,如何在IIS环境下部署https?【转载】]
    div 文章内容自动分屏显示
  • 原文地址:https://www.cnblogs.com/liruoruo/p/10172350.html
Copyright © 2011-2022 走看看