1. 程式人生 > >Vue 新增滑動條監聽

Vue 新增滑動條監聽

在鉤子中新增監聽 

 mounted () {
     const _this = this
     document.documentElement.addEventListener('scroll', _this.handleScroll, true)
 },

 在銷燬前移除監聽

beforeDestroy() {
    const _this = this
    document.documentElement.removeEventListener('scroll', _this.handleScroll, true)
 }

其中呼叫的方法

handleScroll() {
    // 視窗可視高度
    var windowHeight = document.body.clientHeight
    // 視窗實際高度
    var height = document.body.scrollHeight
    // 滑動條移動高度
    var scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
    // 滑動條距離底部距離
    var bottomHeight = height - windowHeight - scrollTop
    if (bottomHeight <= 20) {
        // 呼叫處理方法,可實現懶載入
    }
},