当前位置: 移动技术网 > IT编程>脚本编程>vue.js > vue实现某元素吸顶或固定位置显示(监听滚动事件)

vue实现某元素吸顶或固定位置显示(监听滚动事件)

2018年02月24日  | 移动技术网IT编程  | 我要评论

六合彩31期,东风俊风er30,任意依恋ost

最近写了一个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样式

<div 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>
</div>

固定后的结果:

注意,如果离开该页面需要移除这个监听的事件,不然会报错。

destroyed () {
 window.removeeventlistener('scroll', this.handlescroll)
},

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网