JS如何实现一个类似小程序的onReachBottom触底事件?
Function.prototype.expandMethod = function(name,handle){
!this.prototype[name] && (this.prototype[name] = handle)
return this;
}
HTMLElement.expandMethod('onReachBottom', function(callback, options = { percent: 1 }) {
let containerEl = this;
const isHtmlTag = (el) => Object.prototype.toString.call(el) === '[object HTMLHtmlElement]'
const throttle = (handle, wait = 500) => {
let timer ;
return function(...args){
if(timer){return}
timer = setTimeout(()=>{
handle.call(this,args);
timer = null;
}, wait);
}
}
window.addEventListener('load', () => {
const reachbottom = new CustomEvent("reachbottom", {
detail:{
...options
}
});
containerEl.addEventListener("reachbottom", (e) => {
let target = e.target;
const percent = e.detail.percent;
if(target === window) {
target = document.documentElement;
}
if((target.clientHeight + target.scrollTop) * percent >= target.scrollHeight) {
typeof callback === 'function' && callback.call(e.target, e);
}
});
(isHtmlTag(containerEl) ? window : containerEl).addEventListener('scroll', throttle((e) => containerEl.dispatchEvent(reachbottom)));
})
})
document.querySelector('#list').onReachBottom((e) => {
console.log(e)
})