uni-app 滚动到一定位置固定某个元素在顶部,吸顶解决方案

3,356 阅读1分钟

页面滚动到一定距离固定搜索栏在顶部,大致的思路是先获取节点信息,然后使用uni-app生命周期中onPageScroll监听滚动,当滚动到元素接近顶部位置时添加class,固定该元素。

html部分:
<view class="switchSign"></view>
<!-- 商品搜索s-->
<view class="plr bg pb" :class="{'topfixed-active':topfixed==1}">
	<navigator url="/pages/search/search" class="flex lt whiteBg rds25 plr ptb10">
		<image class="w15 h15 flex ct mr10" src="../../static/index/magnifier.png" mode="widthFix"></image>
		<view class="gray">请输入内容查找</view>
	</navigator>
</view>
<!-- 商品搜索e-->

<!-- 吸顶元素底部内容s-->
 <view :class="{'paTop80':topfixed==1}"></view>
<!-- 吸顶元素底部内容e-->

switchSign在这里是一个标志,用来获取节点信息, 当switchSign滚动接近顶部时topfixed=1,topfixed-active固定样式显示。

实现吸顶的css topfixed-active代码如下,想让谁吸顶就放在谁身上,将switchSign标记放在其上方:
<style>
.topfixed-active {
    width: 100%;
    padding: 0 25upx;
    position: fixed;
    top: var(--window-top);
    left: 0;
    z-index: 9;
    box-sizing: border-box;
}
.paTop80 {
    padding-top: 80px;
}
</style>

js代码:

<script>
    export default{
        data(){
            return{
                topfixed:0,
            }
        },
        onPageScroll(res) {
            var _this=this
            var temptop;
            const query = uni.createSelectorQuery();
            query.select('.switchSign').boundingClientRect();
            query.selectViewport().scrollOffset();
            query.exec(function(res){
                console.log(res);
                res[0].top       // .switchSign节点距离上边界的坐标
                res[1].scrollTop // 显示区域的竖直滚动位置
                temptop=res[0].top;
                if (temptop<='2') {
                    _this.topfixed = 1;  
                }else{
                    _this.topfixed = 0;  
                }  
            })
        },
    }
</script>