为什么我没有得到 scrollTop 值?

Why am I not getting the scrollTop value?

我想获得一个元素的 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>