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>

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

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM