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

最近写了一个VUE的web app项目,需要实现某个部位吸顶的效果。即,页面往上滑动,刚好到达该部位时,该部分,固定在顶部显示。

image.png

1、监听滚动事件

利用VUE写一个在控制台打印当前的scrollTop,

首先,在mounted钩子中给window添加一个滚动滚动监听事件,

mounted () {
  window.addEventListener('scroll', this.handleScroll)
},

然后在方法中,添加这个handleScroll方法

handleScroll () {
  let scrollTop = window.pageYOffset || document.documentElement.scrollTop || 
  document.body.scrollTop
  console.log(scrollTop)
},

2、监听元素到顶部的距离 并判断滚动的距离如果大于了元素到顶部的距离时,设置searchBar为true,否则就是false

handleScroll () {
  let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
  let offsetTop = document.querySelector('#searchBar').offsetTop
  this.searchBarFixed = scrollTop > (offsetTop - 44) // 44px是导航标题头的高度
},

先写一个该元素固定到顶部的样式,isFixed(less写法)

#searchBar{
  .isFixed{
    position:fixed;
    background-color:#fff;
    top:44px; // 44px是导航标题头的高度
    z-index:999;
  }
}

然后将需要固定的元素的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>
 </ul>
</div>

固定后的结果:

image.png

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

destroyed () {
  window.removeEventListener('scroll', this.handleScroll)
},



作者:竿牍
链接:https://www.jianshu.com/p/6f5f6b6c6580
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值