我需要检测用户滚动的方向——“向上”或“向下”。基于此答案中的代码:How can I determine the direction of a jQuery scroll event?
我试图将它包装在一个函数中,这样它就更有区别了——但不幸的是,它不起作用。我认为这与我返回值的方式有关,但方向始终是“向上”。作为 JavaScript 的新手,我在解决这个问题时遇到了问题。
代码如下:
$(document).ready(function () {
'use strict';
var lastScrollTop = 0,
st,
direction;
function detectDirection() {
st = window.pageYOffset;
if (st > lastScrollTop) {
direction = "down";
} else {
direction = "up";
}
lastScrollTop = st;
return direction;
}
$(window).bind('scroll', function() {
detectDirection();
console.log(detectDirection());
});
});
我还设置了一个 Fiddle .
你能帮我找出问题所在吗?
最佳答案
$(window).bind('scroll', function() {
var dir = detectDirection();
console.log(dir);
});
您在每次滚动事件期间调用了两次 detectDirection()
。第一个检测到正确的方向,但第二个只是在同一个地方看到它,所以它返回“向上”,这就是你记录的内容。
关于javascript - jQuery/JavaScript : Detecting scroll direction - code structure issue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15264632/