了解scrollTop
来自scrollTop docs:The vertical scroll position is the same as the number of pixels that are hidden from view ... if the element is not scrollable, this number will be 0.
所以如果你想得到一个非零的值
- 元素必须是可滚动的
- 在此元素内,滚动条必须位于非零位置
在这个codepen example给定这个html
<div id="wrapper">
<h1>Scroll to </h1>
<div id="a">some div</div>
<a id="link" href="#l">click this link</a>
</div>
还有这个 CSS
#wrapper{ overflow-y: scroll;
width:400px; height:200px;
}
div id="wrapper" 是可滚动的,因为使用了 css。如果您现在在div#wrapper 内向下滚动并单击#link,则包装器的滚动条位置将使用
var w = $("#wrapper");
var a = $("#link");
a.click(
function(){
a.text("scrollTop:" + w.scrollTop());
}
);
所以你必须确保scrollTop() 的两个条件都满足才能得到一个非零值
- 元素必须是可滚动的(此处为
div#wrapper)
- 元素必须处于滚动状态(仅当您在#wrapper 内滚动时才会发生)
你可以take a look at this fork 玩弄它。
关于您的问题
scroll 函数是否被触发
要解决您的声明the scroll function wasn't even being called,此example 包含与您类似的代码
<style>
.page{ height: 1200px;}
p { height: 200px; border: 1px solid green;}
</style>
<div class="page">
<h1>Hello Plunker!</h1>
<div>
<p>This is some text</p>
<p>The scroll postion is:<i></i></p>
</div>
</div>
还有这个 javascript
$(window).scroll(function(){
var i = $("i");
i.text($(window).scrollTop());
});
正如您在example 中看到的,代码在您滚动后立即生效。因此,为了能够更好地帮助您,您需要查看完整的代码是否以及为什么它不起作用。
scrollTop 返回零
你写了that the console is only logging 0 despite scrolling down the page。原因可能是您的选择器 $('body#main-page') 匹配不可滚动的元素。没有您的实际代码,我们只能推测。