1. 程式人生 > >小程式 固定分類導航 點選欄目滑動到相應內容

小程式 固定分類導航 點選欄目滑動到相應內容

1:先看一下效果圖,點選對應欄目,頁面滑動到對應的分類內容。

 

2:第一步先實現頁面內容;

<!-- 分類導航 -->
  <view class='nav_fl'>
    <view wx:for="{{goodlist}}" data-index="{{index}}" data-id="b{{index}}" bindtap='tap'>{{item.name}}
      <text class='{{index==navActive?"navactive":""}}'></text>
    </view>
  </view>

 <view style='clear:both;'></view>

<!-- 滾動部分 -->

 <scroll-view class='scrollView' scroll-y="true" scroll-into-view="{{toView}}" style='height:{{height}}rpx;' bindscroll="scroll" scroll-with-animation='true'>
      <view wx:for="{{goodlist}}" wx:for-index="indexOut" id="b{{indexOut}}">
          <view class='listImg'>
            <image style='width:100%;height:290rpx;' src='{{item.img}}'></image>
            <text>已售:200</text>
          </view>
          <view class='listName'>{{item.title}}</view>
          <view class='listId'>{{item.desc}}</view>
      </view>

</scroll-view>

3:設定滑動部分的高度;

onLoad: function(res) {
    var that = this;
    //設定商品列表高度
    wx.getSystemInfo({
      success: function(res) {
        that.setData({
          height: res.windowHeight + 380,
        })
      },
    });
  },

4:點選導航欄目,滑動到對應商品;

  tap: function(e) {
    console.log(e);
    var id = e.currentTarget.dataset.id;
    var index = e.currentTarget.dataset.index;
    this.setData({
      toView: id,
      navActive: index
    });
  },

5:滑動頁面,對應導航active;

//首先要獲取部分內容距離頂部的高度,滑動的時候監聽高度是否到達對應位置;

// 獲取商品列表,生成高度集合
        var height = 0;
        var hightArr = []; 
        for (var i = 0; i < that.data.goodlist.length; i++) { //這裡的goodlist指對應商品集合
            //獲取元素所在位置
          var query = wx.createSelectorQuery();
          var idView="#b"+i;
          query.select(idView).boundingClientRect()
          query.exec(function (res) { 
            var top = res[0].top; 
            hightArr.push(top); 
            that.setData({
              hightArr: hightArr
            });
          });
        } ;


// 頁面滑動到相應位置 對應導航提示
  scroll: function(e) { 
    var scrollTop = e.detail.scrollTop;
    var scrollArr = this.data.hightArr;
    var that=this; 
      for (var i = 0; i < scrollArr.length;i++){
        if (scrollTop >= 0 && scrollTop < scrollArr[0]){ 
          if(0!=this.data.lastActive){ 
            this.setData({
              navActive:0,
              lastActive:0
            })
          }
        } else if (scrollTop >= scrollArr[i - 1] && scrollTop <= scrollArr[i]){  
            if(i!=this.data.lastActive){
              that.setData({
                navActive:i,
                lastActive:i
              })
            }
        }
      }
  },