vue监听滚动事件

vue中监听滚动事件,然后对其进行事件处理,一般有:1. 滚动到顶部吸附; 2. 根据滚动的位置激活对应的tab键(锚链接tab键)

 这两种方式的处理都是可通过监听scroll来实现

mounted(){
    window.addEventListener('scroll',this.handleScroll) // 监听滚动事件,然后用handleScroll这个方法进行相应的处理
},

处理方法

1. 滚动到顶部吸附

html元素

<!--如果isFixed为true的话,就添加class is_fixed 设置固定定位-->
<
div id="boxFixed" :class="{'is_fixed' : isFixed}"> 这个是要滚动到顶部吸附的元素 </div>

methods方法

handleScroll(){
let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop // 滚动条偏移量
let offsetTop = document.querySelector('#boxFixed').offsetTop; // 要滚动到顶部吸附的元素的偏移量
this.isFixed = scrollTop > offsetTop ? true : false; // 如果滚动到顶部了,this.isFixed就为true
}

2. 根据滚动的位置激活对应的tab键(锚链接tab键)

vue里实现锚链接,不能直接用a链接方式,因为用的是hash路由,直接a链接会跳转路由,可用scrollIntoView ,具体参照 https://developer.mozilla.org/zh-CN/docs/Web/API/Element/scrollIntoView

(1) 实现锚链接:

<div class="flexitem" v-for="(item,index) in tabs" :class="seeThis==index?'active':''"><a href="javascript:void(0)" @click="goAnchor(index)">{{item}}</a></div>

<div id="anchor1">block1</div>
<div id="anchor2">block2</div>
<div id="anchor3">block3</div>
data(){
    return{
       seeThis:0,
       tabs:['tab0','tab1','tab2'],
    }
},
methods:{
    goAnchor(index) { // 也可以用scrollIntoView方法, 但由于这里头部设置了固定定位,所以用了这种方法
      // document.querySelector(
'#anchor'+index).scrollIntoView()
      this.seeThis = index; var anchor = this.$el.querySelector('#anchor'+index)
document.body.scrollTop
= anchor.offsetTop-100
document.documentElement.scrollTop
= anchor.offsetTop-100
},
}

(2) 实现滚动到相应的位置激活tab

methods:{
handleScroll(){
   var anchorOffset0 = this.$el.querySelector('#anchor0').offsetTop-100
   var anchorOffset1 = this.$el.querySelector('#anchor1').offsetTop-100
var anchorOffset2 = this.$el.querySelector('#anchor2').offsetTop-100
   if(scrollTop>anchorOffset0&&scrollTop<anchorOffset1){
    this.seeThis = 0
   }
   if(scrollTop>anchorOffset1&&scrollTop<anchorOffset2){
    this.seeThis = 1
   }
   if(scrollTop>anchorOffset2){
    this.seeThis = 2
   }
},
}
原文地址:https://www.cnblogs.com/leiting/p/10337313.html