vue中監聽頁面滾動和監聽某元素滾動


①監聽頁面滾動

在生命周期mounted中進行監聽滾動:

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

在方法中定義監聽滾動執行的方法:

scrollToTop() { 
  var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
  console.log(scrollTop)
},

記得在離開當前路由解綁scroll事件

  beforeRouteLeave(to, form, next){
    window.removeEventListener('scroll',this.scrollToTop);
    next();
  }

②監聽某元素滾動

需要監聽的這個元素需要擁有固定的高度

vue組件中:


<div class="read-con"  @scroll="scrollEvent" >
</div>

在方法中定義scrolldiv,是監聽class為read-con滾動以后需要執行的方法

scrollEvent () {
      let _this = this
      let read = _this.$el.querySelector('#read')
      console.log(read.scrollToTop)
},

③ 獲取各個元素高度
獲取具體一個元素的真實高度:
使用scrollHeight的時候,如果scrollHeight小於offsetHeight的時候,高度就是offsetHeight,只有超過offsetHeight的時候才是scrollHeight的高度,不管隱藏不隱藏內容

    // 文檔高度
    let docHeight = document.querySelector('.page').scrollHeight;

獲取窗口高度:

    // 窗口高度
    let winHeight = document.body.offsetHeight;


免責聲明!

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



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