jQuery/JavaScript:检测滚动方向 - 代码结构问题

Sve*_*ven 12 javascript jquery scroll return code-structure

我需要检测用户滚动的方向 - "向上"或"向下".基于此答案中的代码:如何确定jQuery滚动事件的方向?

我试图将它包装在一个函数中,因此它有点区别 - 但不幸的是,它不起作用.我认为它与我如何返回值有关,但方向总是"向上".作为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());

    });

});
Run Code Online (Sandbox Code Playgroud)

我也建立了一个小提琴.

你能帮我找一下问题所在吗?

Bar*_*mar 6

$(window).bind('scroll', function() {

    var dir = detectDirection();
    console.log(dir);

});
Run Code Online (Sandbox Code Playgroud)

detectDirection()在每个滚动事件期间都要调用两次.第一个检测到正确的方向,但第二个只是在同一个地方看到它,所以它返回"up",这就是你记录的内容.