繁体   English   中英

滚动到特定 div 底部后如何触发 javascript function?

[英]How to fire javascript function after scroll to specific div bottom?

 window.addEventListener("scroll", ()=>{ alert('you passed red box bottom') })
 .first-box{height:200px; width:300px; border:1px solid red}.second-box{ height:200px; width:300px; border:1px solid blue margin-top:140px; }
 <div class="first-box"></div> <div class="second-box"></div>

嗨,我正在使用 Vanilla JS 创建简单的应用程序,遇到了问题,我滚动了 function,我只想在用户将通过红色框底部时触发它,我尝试使用element.offsetBottom ,但不幸的是什么也没发生out,我想解决这个问题只有纯javascript,PS div高度不是static 可以增加,根据内容,有什么解决办法吗?

要到达您想要的容器底部,您需要使用该容器的参数scrollHeight 此外,如果您比较 window.scrollY 的当前window.scrollY直到此 position 等于element.scrollHeight ,则使用该条件。

 var firstbox = document.querySelector(".first-box"); window.addEventListener("scroll", () => { if (this.scrollY >= firstbox.scrollHeight) { console.log('you passed red box bottom'); } });
 body { height: 5000px; }.first-box { height:200px; width:300px; border:1px solid red; }.second-box { height:200px; width:300px; border:1px solid blue margin-top:140px; }
 <div class="first-box"></div> <div class="second-box"></div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM