2 回答

TA貢獻(xiàn)1866條經(jīng)驗(yàn) 獲得超5個(gè)贊
正如@bertida 所述,要實(shí)現(xiàn)這一點(diǎn),getBoundingClientRect().top應(yīng)該使用而不是scrollTop.
<!DOCTYPE html>
<html>
<head></head>
<body onscroll="get_y_pos();">
<div style="height: 400px; width: 300px; background: red; margin: 20px;"></div>
<div style="height: 400px; width: 300px; background: red; margin: 20px;"></div>
<div id="element_to_watch" style="height: 400px; width: 300px; background: blue; margin: 20px;"></div>
<div style="height: 400px; width: 300px; background: red; margin: 20px;"></div>
<div style="height: 400px; width: 300px; background: red; margin: 20px;"></div>
</body>
<script>
function get_y_pos() {
var pos = document.getElementById('element_to_watch').getBoundingClientRect().top;
console.log(pos);
}
</script>
</html>

TA貢獻(xiàn)1798條經(jīng)驗(yàn) 獲得超7個(gè)贊
正如有人已經(jīng)說(shuō)過(guò)的那樣,您需要向元素添加垂直滾動(dòng)條才能檢查其scrollTop值。檢查更新的代碼片段。
<!DOCTYPE html>
<html>
<head></head>
<body onscroll="get_y_pos();" style="overflow: visible;">
<div style="height: 400px; width: 300px; background: red; margin: 20px;"></div>
<div style="height: 400px; width: 300px; background: red; margin: 20px;"></div>
<div id="element_to_watch" style="height: 300px; width: 300px; background: blue; margin: 20px; overflow-y: scroll;">
<h1 style="height: 500px">Hallo</h1>
</div>
<div style="height: 400px; width: 300px; background: red; margin: 20px;"></div>
<div style="height: 400px; width: 300px; background: red; margin: 20px;"></div>
</body>
<script>
function get_y_pos() {
var pos = document.getElementById('element_to_watch');
console.log(pos.scrollTop);
}
</script>
</html>
添加回答
舉報(bào)