【发布时间】:2016-04-09 14:48:14
【问题描述】:
我正在使用 jquery 函数 element.scrollTop() 使用以下行获取页面的当前滚动位置:
var currentScrollPosition= $('html').scrollTop() || $('body').scrollTop();
但它总是返回上一个滚动位置的值。请检查下面的代码(与in here 相同)。 正如您可以自己尝试并在代码中看到的那样,在每次微小滚动之后,我们都会得到以下一系列值:
(1:当代码第一次运行并且还没有移动时)
增量:0
累积增量:0
functionCallCount:0
当前滚动位置:0
(delta 给出滚动量,cumulativeDelta 给出滚动总量,functionCallCount 是您滚动的次数,currentScrollPosition 是 scrolltop() 返回的值)
(2:稍微滚动时)
增量:-120
累积增量:-120
functionCallCount:1
当前滚动位置:0
(注意这里,currentScrollPosition 还没有更新)
(3:再滚动一点)
增量:-120
累积增量:-240
functionCallCount:2
当前滚动位置:90.90908893868948
(这里,累积增量,即到目前为止所做的总滚动量加倍,并且 currentScrollPosition 是第一次更新)
(4:再滚动一点)
增量:-120
累积增量:-360
functionCallCount:3
当前滚动位置:181.81817787737896
(现在,cumulativeDelta 增加了三倍,而 currentScrollPosition 增加了一倍。因此,这是两次滚动后的值,但在 3 次滚动后更新)
我为冗长的问题道歉,但否则很难问。我想知道为什么会发生这种情况,如果我应该以其他方式使用此功能,还有其他替代方法。
document.addEventListener("mousewheel", MouseWheelHandler);
var cumulativeDelta = 0,
functionCallCount = 0;
function MouseWheelHandler(e) {
e = window.event || e; // 'event' with old IE support
var delta = e.wheelDelta || -e.detail; // get delta value
cumulativeDelta += delta;
functionCallCount += 1;
currentScrollPosition = $('html').scrollTop() || $('body').scrollTop();
document.getElementById("info1").innerHTML = "delta:" + delta;
document.getElementById("info2").innerHTML = "cumulativeDelta:" + cumulativeDelta;
document.getElementById("info3").innerHTML = "functionCallCount:" + functionCallCount;
document.getElementById("info4").innerHTML = "currentScrollPosition:" + currentScrollPosition;
}
body {
height: 2000px;
border: solid red 3px;
}
.normalPart {
border: solid green 2px;
height: 900px;
}
.stationary {
position: fixed;
top: 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<div class="stationary">
<div id="info1"></div>
<div id="info2"></div>
<div id="info3"></div>
<div id="info4"></div>
</div>
【问题讨论】:
标签: javascript jquery html scroll scrolltop