今天在写后台管理系统时,遇到一个需求:
需求:当页面滚动的距离超过当前dom与顶部的距离后,当前dom元素需要固定在页面顶部。
此时需要用到window.addEventListener
的方法,来监听页面的滚动。
1.window.addEventListener
监听滚动事件
data(){
return{
timer:null,
isFixed:false,
}
},
mounted(){
this.$nextTick(()=>{
const dom = this.$refs.buttonBoxSelf.$el;
let offsetTop = dom.offsetTop;
window.addEventListener(
'scroll',
e=>{
let scrollTop = e.target.scrollTop;
if(this.timer){
clearTimeout(this.timer)
}
this.timer = setTimeout(()=>{
//滚动距离为包裹层距离内容层的高度
if(scrollTop >= offsetTop){
this.isFixed = true;
}else{
this.isFixed = false;
}
},10)
},true
)
})
}
注意上面的方法,是通过定时器来判断是否要固定到顶部的。
2. dom
绑定固定定位的样式
<a-card :class="{
'button-box-fixed':isFixed}">
//需要固定到顶部的元素
</a-card>
3. css
样式
.button-box-fixed {
position: fixed;
top: 90px;//这个需要根据实际情况来调整
z-index: 3;
width: calc(100% - 120px);
box-shadow: 0 6px 12px 0 rgb(0 0 0 / 5%);
}