方法一:

1,wxml
<view wx:if="{{ scrollTop >= 300 }}" class='itemBox'></view>
<view class="{{scrollTop >= 300 ? 'topnavFixed' : 'proItem'}}">
? ? <!-- 內(nèi)容 -->
</view>
.proItem {
? background: #ffffff;
? z-index: 111;
? padding-left: 35rpx;
? height: 75rpx;
? border-top: 1rpx solid #f5f5f5;
? border-bottom: 1rpx solid #f5f5f5;
? box-sizing: border-box;
}
.itemBox{
? height: 75rpx;
}
.topnavFixed{
? background: #ffffff;
? z-index: 1111111;
? position: fixed;
? top: 0;
? height: 75rpx;
? width: 100%;
? padding-left: 35rpx;
? border-top: 1rpx solid #f5f5f5;
? border-bottom: 1rpx solid #f5f5f5;
}
2,js
onPageScroll(e) {
console.log(e);
vartop = e.scrollTop;
this.setData({
scrollTop:top
? ? })
? },
注意:
此方法只適用于分類部分在頂部的位置,因?yàn)?00是具體值,所以做不到兼容各個(gè)型號(hào);
方法二:
1,整體布局代碼
<scroll-view scroll-y='true' style='height:100%;' bindscroll="scroll">
? <view>
? ? <view class="container">
? ? ? <view class='box' hidden='{{!hidFirstView}}'>
? ? ? ? <view class='boxHeight'>
? ? ? ? ? <!-- 輪播圖 -->
? ? ? ? ? <view class='banner'></view>
? ? ? ? ? <!-- 四個(gè)大按鈕 -->
? ? ? ? ? <view class='buttonView'></view>
? ? ? ? </view>
? ? ? ? <!-- 商品分類 -->
? ? ? ? <view wx:if="{{ scrollTop >= boxHeight }}" class='itemBox'></view>
? ? ? ? <view class="{{scrollTop >= boxHeight ? 'topnavFixed' : 'proItem'}}">
? ? ? ? </view>
? ? ? ? <!-- 商品列表 -->
? ? ? ? <view class='proList' data-id='{{ item.id }}' bindtap='a' wx:for="{{productList}}">
? ? ? ? </view>
? ? ? </view>
? ? </view>
</scroll-view>
2,js代碼
scroll:function(e){
? this.setData({
? ? scrollTop: e.detail.scrollTop
? })
},
//根據(jù)元素id獲取元素高度,若此處元素是數(shù)據(jù)渲染生成的,則需要在頁(yè)面渲染完成之后執(zhí)行此方法,不然頁(yè)面沒渲染完成獲取的這個(gè)元素高度會(huì)是0
var query = wx.createSelectorQuery();
? ? //選擇id
? ? query.select('.boxHeight').boundingClientRect(function (rect) {
? ? that.setData({
? ? ? boxHeight: rect.height
? ? })
}).exec();
注意:
頁(yè)面有的模塊是經(jīng)過請(qǐng)求數(shù)據(jù)后渲染出來(lái)的,此時(shí)若每個(gè)元素外層已經(jīng)套了一層有固定高度的父元素,則? wx.createSelectorQuery 獲取到 boxHeight 的高度就不會(huì)受渲染前后的影響;
若沒有在外層套固定高度的父元素,此時(shí) boxHeight 的高度就會(huì)受數(shù)據(jù)渲染速度影響。
建議:
要么,外層套一個(gè)有固定高度的父元素;
要么,在該請(qǐng)求數(shù)據(jù)接口成功的回調(diào)函數(shù)里使用?wx.createSelectorQuery;
文章來(lái)源:https://blog.csdn.net/weixin_42157001/article/details/93166305