JS实现一个类似小程序的onReachBottom触底事件

JS如何实现一个类似小程序的onReachBottom触底事件?

Function.prototype.expandMethod = function(name,handle){
	!this.prototype[name] && (this.prototype[name] = handle)
    return this;
}

/**
* 如果是整体页面的滚动,containerEl请指定为html,
 * 其它情况下,为滚动容器本身
 * 
*/
HTMLElement.expandMethod('onReachBottom', function(callback, options = { percent: 1 }) {
   let containerEl = this;
   // 是否是html标签
   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);
       }
   }
   //onReachBottom的副作用,就是load事件会产生的一个影响 
   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)
})
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值