簡體   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