天天看点

微信小程序--特定区域滚动到顶部时固定

项目要求:

微信小程序--特定区域滚动到顶部时固定
微信小程序--特定区域滚动到顶部时固定

如图所示,当页面滚动到导航条到达搜索栏下方时固定,向上滚动到导航条位置时又恢复原样。

以下是代码展示:

1.wxml

<scroll-view style="width:100%;height: 100%;" scroll-y="true" bindscroll="scrollTopFun">
    <view class="{{top>130 ? 'topnav' : ''}}">
    <--这里写大于,表示距离顶部130rpx时固定,可根据需要修改-->
        ...
    </view>
</scroll-view>
           

2.wxss

.topnav{
    position: fixed;
    top: rpx;
    z-index:;
    background: #fff;
    width: %;
}
           

3.js

data = {
  top:0
}
//控制回到顶部按钮的显示与消失
scrollTopFun(e){
    let that = this;
    that.top = e.detail.scrollTop;
    that.$apply();
}
           

其实整个思路很简单, 小程序自带的组件scroll-view自带有属性bindscroll(滚动时触发)。通过这个属性获取浏览器滚动条距离顶部的位置,通过这个位置判断class类的显示就可以了。