为什么我没有得到 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>


潇潇雨雨
浏览 239回答 2
2回答

心有法竹

正如@bertida 所述,要实现这一点,getBoundingClientRect().top应该使用而不是scrollTop.<!DOCTYPE html><html><head></head><body onscroll="get_y_pos();">&nbsp; <div style="height: 400px; width: 300px; background: red; margin: 20px;"></div>&nbsp; <div style="height: 400px; width: 300px; background: red; margin: 20px;"></div>&nbsp; <div id="element_to_watch" style="height: 400px; width: 300px; background: blue; margin: 20px;"></div>&nbsp; <div style="height: 400px; width: 300px; background: red; margin: 20px;"></div>&nbsp; <div style="height: 400px; width: 300px; background: red; margin: 20px;"></div></body>&nbsp; <script>&nbsp; &nbsp; function get_y_pos() {&nbsp; &nbsp; &nbsp; var pos = document.getElementById('element_to_watch').getBoundingClientRect().top;&nbsp; &nbsp; &nbsp; console.log(pos);&nbsp; &nbsp; }&nbsp; </script></html>

元芳怎么了

正如有人已经说过的那样,您需要向元素添加垂直滚动条才能检查其scrollTop值。检查更新的代码片段。<!DOCTYPE html><html><head></head><body onscroll="get_y_pos();" style="overflow: visible;">&nbsp; <div style="height: 400px; width: 300px; background: red; margin: 20px;"></div>&nbsp; <div style="height: 400px; width: 300px; background: red; margin: 20px;"></div>&nbsp; <div id="element_to_watch" style="height: 300px; width: 300px; background: blue; margin: 20px; overflow-y: scroll;">&nbsp; &nbsp; <h1 style="height: 500px">Hallo</h1>&nbsp; </div>&nbsp; <div style="height: 400px; width: 300px; background: red; margin: 20px;"></div>&nbsp; <div style="height: 400px; width: 300px; background: red; margin: 20px;"></div></body>&nbsp; <script>&nbsp; &nbsp; function get_y_pos() {&nbsp; &nbsp; &nbsp; var pos = document.getElementById('element_to_watch');&nbsp; &nbsp; &nbsp; console.log(pos.scrollTop);&nbsp; &nbsp; }&nbsp; </script></html>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript