微信小程序吸頂功能


---------------------------HTML------------------------

<view class="navbar-wrap">
  <view class="column {{isFixedTop?'fixed':''}}" id="navbar">
    <view class="block active">新品推薦</view>
    <view class="block">限時優惠</view>
    <view class="block">火爆熱搜</view>
    <view class="block">猜你喜歡</view>
  </view>
  <!-- 用於吸頂后 占位用的 -->
  <view class="column" wx:if="{{isFixedTop}}"></view>
</view>


<view class="list {{isFixedTop?'martop':''}}">列表數據</view>

---------------------------CSS------------------------

.navbar-wrap {
  width: 100%;
}

.navbar-wrap .column {
  width: 100%;
  height: 80rpx;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-around;
  background: #fff;
  border-bottom: solid 1px #eee;

  top: 0;

  left: 0;
  z-index: 100;
}

.navbar-wrap .column.fixed {
 position: fixed;
}

.martop{

  margin-top: "吸頂對象的高度"

}

------------------------JS-------------------------

Page({
data: {
  navbarInitTop: 0, //導航欄初始化距頂部的距離
  isFixedTop: false, //是否固定頂部
},

/**
* 生命周期函數--監聽頁面加載
*/
onLoad: function(options) {

},

/**
* 生命周期函數--監聽頁面顯示
*/
onShow: function() {
  var that = this;

  if (that.data.navbarInitTop == 0) {

   //獲取節點距離頂部的距離
   wx.createSelectorQuery().select('#navbar').boundingClientRect(function(rect) {
    if (rect && rect.top > 0) {
      var navbarInitTop = parseInt(rect.top);
      that.setData({
      navbarInitTop: navbarInitTop
      });
    }
   }).exec();

  }
},

/**
* 監聽頁面滑動事件
*/
onPageScroll: function(e) {
 var that = this;
 var scrollTop = parseInt(e.scrollTop); //滾動條距離頂部高度

 //判斷'滾動條'滾動的距離 和 '元素在初始時'距頂部的距離進行判斷
 var isSatisfy = scrollTop >= that.data.navbarInitTop ? true : false;
 //為了防止不停的setData, 這兒做了一個等式判斷。 只有處於吸頂的臨界值才會不相等
 if (that.data.isFixedTop === isSatisfy) {
  return false;
 }

 that.setData({
  isFixedTop: isSatisfy
 });
}

})


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM