为什么我没有得到scrollTop值?

问题描述

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...