代码实现:
html中,设置id,v-bind:class名,如下:
<ul class="box_fixed" id="boxFixed" :class="{'is_fixed' : isFixed}"></ul>
js:监听鼠标行为
data() {
return {
isFixed: false,
offsetTop: 0
}
},
mounted() {
window.addEventListener('scroll', this.initHeight);
this.$nextTick(() => {
//获取对象相对于版面或由 offsetTop 属性指定的父坐标的计算顶端位置
this.offsetTop = document.querySelector('#boxFixed').offsetTop;
})
},
methods: {
initHeight() {
// 设置或获取位于对象最顶端和窗口中可见内容的最顶端之间的距离 (被卷曲的高度)
var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
//如果被卷曲的高度大于吸顶元素到顶端位置 的距离
this.isFixed = scrollTop > this.offsetTop ? true : false;
},
},
//回调中移除监听
destroyed() {
window.removeEventListener('scroll', this.handleScroll)
}
css:设置吸顶元素宽高及实现吸顶时的 position: fixed;
.box_fixed{
width: 500px;
height: 40px;
border: 2px dashed pink;
border-radius: 20px;
margin: 0 auto;
line-height: 40px;
background: #eeeeee;
}
.is_fixed{
position: fixed;
top: 0;
z-index: 999;
}
效果图:
参考:
1、Vue-实现吸顶效果