如何从元素中获取scrollTop?

时间:2018-01-17 07:24:03

标签: javascript

我有一个div元素,其中包含一些其他元素,如p标签和菜单。我希望菜单在菜单中添加一个类,当用户向下滚动约100个像素时。所以我试图弄清楚如何获得滚动的距离。

<script type="text/javascript">
  var x = document.getElementById("scrollElement");

  function myFunction() {
    alert(x.scrollTop);
  }
</script>

我创造了一个模拟情况的傻瓜。问题是,当我滚动并检查scrollTop值时,它会输出0

这是plunkr

为什么选择downvote?这是一个普通的javascript问题,它有一个明确的例子:/

2 个答案:

答案 0 :(得分:1)

试试这个

//代码在这里

window.addEventListener('scroll',function(){
  let scrollTop=document.body.scrollTop || document.documentElement.scrollTop;
     if(scrollTop>100){alert(scrollTop)}
},false);

答案 1 :(得分:1)

Element.scrollTop基本上是DIV顶部边框与DIV最顶部可见线之间的距离。为了更好地理解read this

&#13;
&#13;
var container = document.querySelector(".container"),
    p         = document.querySelector("p.child");
    
container.addEventListener('scroll', function() {
  if(container.scrollTop > 100)
    p.classList.add('red');
  else
    p.classList.remove('red');
});
&#13;
.container {
  max-height: 200px;
  border: 1px solid black;
  overflow-y: auto;
}

h1.child {
  text-align: center;
  height: 400px;
}

p.child.red {
  color: red;
}
&#13;
<div class="container">
  <h1 class="child">HELLO!</h1>
  <p class="child">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>
&#13;
&#13;
&#13;