快活林资源网 Design By www.csstdc.com

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 "external nofollow" target="_blank" href="https://developer.mozilla.org/zh-CN/docs/Web/API/Element/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"><a href="javascript:void(0)" rel="external nofollow" @click="goAnchor(index)">{{item}}</a></div>

<div id="anchor1">block1</div>

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

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
  },
}
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
    }
  },
}

以上就是vue监听滚动事件的方法的详细内容,更多关于vue监听滚动事件的资料请关注其它相关文章!

快活林资源网 Design By www.csstdc.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
快活林资源网 Design By www.csstdc.com