1. 程式人生 > 程式設計 >vue監聽滾動事件的方法

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)" 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監聽滾動事件的資料請關注我們其它相關文章!