jquery scrolltop()返回上一个滚动位置的值
我使用jquery函数element.scrollTop()
来使用以下行获取页面的当前滚动位置:
var currentScrollPosition= $('html').scrollTop() || $('body').scrollTop();
但它总是返回前一个滚动位置的值。 请检查下面的代码(与此处的代码相同)。 正如您可以尝试自己并在代码中看到的,在每个小滚动之后,我们得到以下一系列值:
(1:代码首次运行时尚无动作)
增量:0
cumulativeDelta:0
functionCallCount:0
currentScrollPosition:0
(delta给出滚动多少,cumulativeDelta给出滚动总量,functionCallCount是滚动的次数,currentScrollPosition是scrolltop()返回的值)
(2:滚动一点时)
三角洲:-120
cumulativeDelta:-120
functionCallCount:1
currentScrollPosition:0
(请注意,currentScrollPosition仍未更新)
(3:进一步滚动时)
三角洲:-120
cumulativeDelta:-240
functionCallCount:2
currentScrollPosition:90.90908893868948
(这里,cumulativeDelta,是目前为止所做的总滚动的加法,加倍,并且currentScrollPosition首次更新)
(4:滚动时多一点)
三角洲:-120
cumulativeDelta:-360
functionCallCount:3
currentScrollPosition: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; }
问题是因为当鼠标滚轮开始运动时鼠标滚轮事件会触发。 您正在更新发生之前阅读scrollTop
。 鼠标滚轮滚动完成后 ,您需要使用计时器来获取scrollTop
。 试试这个:
document.addEventListener("mousewheel", MouseWheelHandler); var cumulativeDelta = 0, functionCallCount = 0, currentScrollPosition = 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; setTimeout(function() { currentScrollPosition = $(window).scrollTop(); document.getElementById("info4").innerHTML = "currentScrollPosition:" + currentScrollPosition; }, 200); // update currentScrollPos 200ms after event fires document.getElementById("info1").innerHTML = "delta:" + delta; document.getElementById("info2").innerHTML = "cumulativeDelta:" + cumulativeDelta; document.getElementById("info3").innerHTML = "functionCallCount:" + functionCallCount; }
body { height: 2000px; border: solid red 3px; } .normalPart { border: solid green 2px; height: 900px; } .stationary { position: fixed; top: 0px; }