当我们页面滑动到一定位置的时候,让这个组件固定,之后再滑动到一定位置时候,回归原页面,还有点击立即到最顶部效果
如果是移动端的话,可以用一个position: sticky;不过要考虑兼容性
uniapp怎么做呢?
比如想让这个组件,滑动到一定位置吸顶
<Delicacy id="boxFixed" :class="{'is_fixed' : isfixed}"></Delicacy>
data(){
return{
rect:'' //页面滚动距离
menutop:'' //组件距离顶部的距离
}
}
首先监听页面滚动距离
onPageScroll(e) {
// console.log(e.scrollTop)
this.rect = e.scrollTop
},
然后监听组件距离顶部的距离
onLoad() {
// 监听筛选组件距离顶部的距离
const query = uni.createSelectorQuery()
query.select('#boxFixed').boundingClientRect()
query.exec((res) => {
this.menutop = res[0].top
})
},
然后通过computed计算
computed: {
// 监听筛选组件置顶和不置顶
namepage() {
// 如果页面滚动的高度大于筛选组件距离顶部的高度,那就置顶,反之不置顶
if (this.rect > this.menutop) {
this.isfixed = true
} else {
this.isfixed = false
}
},
},
css
.is_fixed {
position: fixed;
left: 0;
top: 0;
right: 0;
}
这样就完成了吸顶效果,如果我们想点击这个组件,它立即回到顶部呢?
<view @click="poll()" :catchtouchmove="true">
<Delicacy id="boxFixed" :class="{'is_fixed' : isfixed}"></Delicacy>
</view>
data(){
return{
topdata:''
}
}
methods:{
// 回到顶部
poll() {
uni.pageScrollTo({
scrollTop: this.topdata + 2,
duration: 300
})
},
},
onLoad() {
// 监听筛选组件距离顶部的距离
const query = uni.createSelectorQuery()
query.select('#boxFixed').boundingClientRect()
query.exec((res) => {
this.topdata = res[0].top
})
},
这样即可