2 回答
TA贡献1866条经验 获得超5个赞
正如@bertida 所述,要实现这一点,getBoundingClientRect().top应该使用而不是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贡献1798条经验 获得超7个赞
正如有人已经说过的那样,您需要向元素添加垂直滚动条才能检查其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>
添加回答
举报