本文主要为大家详细介绍了vue实现某元素吸顶或固定位置显示,监听滚动事件,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能帮助到大家。
最近写了一个vue的web app项目,需要实现某个部位吸顶的效果。即,页面往上滑动,刚好到达该部位时,该部分,固定在顶部显示。
1、监听滚动事件
利用vue写一个在控制台打印当前的scrolltop,
首先,在mounted钩子中给window添加一个滚动滚动监听事件,
mounted () {
window.addeventlistener('scroll', this.handlescroll)
},
然后在方法中,添加这个handlescroll方法
handlescroll () {
var scrolltop = window.pageyoffset || document.documentelement.scrolltop || document.body.scrolltop
console.log(scrolltop)
},
控制台打印结果:
2、监听元素到顶部的距离 并判断滚动的距离如果大于了元素到顶部的距离时,设置searchbar为true,否则就是false
handlescroll () {
var scrolltop = window.pageyoffset || document.documentelement.scrolltop || document.body.scrolltop
var offsettop = document.queryselector('#searchbar').offsettop
if (scrolltop > offsettop) {
this.searchbarfixed = true
} else {
this.searchbarfixed = false
}
},
先写一个该元素固定到顶部的样式,isfixed(less写法)
.searchbar{
.isfixed{
position:fixed;
background-color:#fff;
top:0;
z-index:999;
}
ul {
width:100%;
height: 40px;
line-height: 40px;
display: flex;
li {
font-size: 0.8rem;
text-align: center;
flex: 1;
i {
font-size: 0.9rem;
padding-left: 5px;
color: #ccc;
}
}
border-bottom: 1px solid #ddd;
}
}
然后将需要固定的元素的class与searchbar进行绑定,如果searchbar为true时,就应用这个isfixed样式
<p class="searchbar" id="searchbar">
<ul :class="searchbarfixed == true ? 'isfixed' :''">
<li>区域<i class="iconfont icon-jiantouxia"></i></li>
<li>价格<i class="iconfont icon-jiantouxia"></i></li>
<li>房型<i class="iconfont icon-jiantouxia"></i></li>
<li>更多<i class="iconfont icon-jiantouxia"></i></li>
</ul>
</p>
固定后的结果:
注意,如果离开该页面需要移除这个监听的事件,不然会报错。
destroyed () {
window.removeeventlistener('scroll', this.handlescroll)
},
相关推荐:
关于javascript如何实现导航栏吸顶操作的实例分享
js实现导航吸顶效果
实现tab吸顶使用react.js中的问题
以上就是vue监听滚动事件某元素吸顶或固定位置显示详解的详细内容。