addEventListener 的使用

例如監聽頁面滾動條的位置css

一、html 中定義(獲取div高度)html

<div class="content" >
  <div class="approval-list" ref="scrollBox"> </div>
</div>

二、mounted() 方法app

【注 1】監聽div滾動條的高度:建立一個監聽就要記得銷燬,不然屢次加載致使頁面奔潰dom

  mounted () {
    this.$nextTick(() => {
      this.$refs.scrollBox.addEventListener('scroll', this.handleScroll)
    })
  },

【注 2】因爲 mounted() 階段 dom 節點才被渲染,所以若是初始化高度、獲取高度等操做應該寫在 mounted() 方法中this

 let h1 = this.$refs.scrollBox.offsetHeight  // 500 (沒有單位)
 let h2 = this.$refs.scrollBox.style.height  // 500px (以‘px’爲單位)

 

三、methods() 方法spa

  methods: {
    // 獲取滾動條高度
    handleScroll() {
      localStorage.setItem('scrollBox', this.$refs.scrollBox.scrollTop)
    },
    // 還原滾動條高度
    getBeforeScroll() {
      let _this = this
      _this.$nextTick(function () {
        var scrollTop = Number(localStorage.getItem("scrollBox"))
        if (scrollTop) {
          this.$refs.scrollBox.scrollTop = scrollTop
        }
      });
    },
  },

四、addEventListener事件 註冊了就必定要記得銷燬,在 beforeDestroy() 中銷燬事件。code

 beforeDestroy () {
    this.$refs.scrollBox.removeEventListener('scroll', 
    this.handleScroll)
  }

這是對document的監聽事件是一個全局的操做,若是沒有手動的去取消這個監聽那麼它的監聽機制也就一直存在着,這樣每次進入這個頁面也就意味着都會增長一次對它的監聽。屢次以後天然頁面也就會卡死了。htm

 

五、【注】若是addEventListener()事件 監聽方法不執行blog

檢查幾個問題:事件

1. 監聽滾動的元素結點是否給了height和overflow:scroll

2. 監聽滾動的元素結點的父元素結點是否設置了高度

例如css代碼以下:

<style scoped>
.content {
  height: 100%;
}
.approval-list {
  overflow-y: auto;
}
</style>

 

相關文章
相關標籤/搜索