簡體   English   中英

如何使用JS計算div而不是整個頁面的滾動百分比?

[英]How can I calculate scroll percentage of a div instead of whole page with JS?

我發現以下代碼可用來在您向下滾動頁面時跟蹤滾動百分比。

document.addEventListener('scroll', function(){

var h = document.documentElement, 
    b = document.body,
    st = 'scrollTop',
    sh = 'scrollHeight';

var percent = (h[st]||b[st]) / ((h[sh]||b[sh]) - h.clientHeight) * 100;

document.getElementById('scroll').textContent = 'scrolled: ' + percent + '%';

});

這顯示了整個頁面的百分比。 如果我只想要特定div的滾動百分比,例如此示例https://www.thefarmersdog.com/ ,則在向下移動頁面時,狗碗如何滾動。

您需要使用getBoundingClientRect()

const coordinates = document.getElementById('your-id').getBoundingClientRect();
console.log(coordinates.top); // This is the distance to the top of the screen

如果需要更多信息,可以閱讀這里的詳細文章

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM