问题描述
我想获取一个元素的 scrollTop 值,这样我就可以触发其他操作。客户端应始终检查 scrollTop 值,因此我正在使用 onscroll 来运行该功能。它不起作用,我总是得到0。
<!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').scrollTop;
console.log(pos);
}
</script>
</html>
解决方法
就像有人已经说过的那样,您需要向元素添加垂直滚动条,以检查其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>
,
如@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>