Skip to content

Latest commit

 

History

History
93 lines (83 loc) · 2.81 KB

触底刷新.md

File metadata and controls

93 lines (83 loc) · 2.81 KB

function debounce(func, wait) { var timeout; return function () { var _this = this; var args = arguments;

    clearTimeout(timeout);
    timeout = setTimeout(function () {
        func.apply(_this, args);
    }, wait);
};

}

class ScrollEnd { constructor(wrapEle, conEle, callback = () => {}, offset = 300) { const options = wrapEle if (options && typeof options === 'object') { this.wrapEle = options.wrapEle this.conEle = options.conEle this.callback = options.callback this.offset = options.offset } else { this.wrapEle = wrapEle this.conEle = conEle this.callback = callback this.offset = offset } // 延迟100ms获取元素,防止在created钩子初始化实例 setTimeout(() => { if (typeof this.wrapEle === 'string') this.wrapEle = document.querySelector(this.wrapEle) if (typeof this.conEle === 'string') this.conEle = document.querySelector(this.conEle) if (!this.wrapEle || !this.conEle) { console.error('wrapEle or conEle should be required') return } this.init(this.wrapEle, this.conEle, this.callback, this.offset) }, 100) }

init ($wrapEle, $conEle, callback, offset) {
    // 滚动刷新数据
    try {
        // 滚动视口高度
        let wrapOffsetHeight = $wrapEle.offsetHeight
        // 滚动内容高度
        let conOffsetHeight = $conEle.offsetHeight
        let fn = debounce(event => {
            const {scrollTop} = event.target
            if (scrollTop + wrapOffsetHeight > conOffsetHeight - offset) {
                callback && callback()
            }
        }, 100)

        $wrapEle.addEventListener('scroll', fn)

        this.init.destroy = () => {
            $wrapEle.removeEventListener('scroll', fn)
        }

        this.init.reflesh = () => {
            setTimeout(() => {
                conOffsetHeight = $conEle.offsetHeight
            }, 100)
        }
    } catch (e) {
        console.error(e)
    }
}

reflesh () {
    this.init.reflesh()
}

destroy () {
    this.init.destroy()
}

}

export default ScrollEnd

/**

  • example:
  • const scrollEnd = new ScrollEnd(wrapEle, conEle, callback, offset)
  •  wrapEle: (String|Element)滚动外层元素
    
  •  conEle: (String|Element)滚动内容元素
    
  •  callback: (Function)滚动到底需要执行的回调
    
  •  offset: (Number)偏移量,距离底部的距离
    
  • 方法:
  • scrollEnd.reflesh: 当内容高度发生变化时,可以执行这个函数
  • scrollEnd.destroy: 销毁滚动的监听
  • */