javascript - jQuery/JavaScript : Detecting scroll direction - code structure issue

标签 javascript jquery scroll return code-structure

我需要检测用户滚动的方向——“向上”或“向下”。基于此答案中的代码: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/

相关文章:

javascript - 无法从 jQuery.ajax 成功函数返回值

jquery - 有没有办法选择 cheerio 中的每个元素?

jquery - 防止 jQuery spritely 平移 <div> 以增加页面长度

jquery - 如何更改元素在滚动条上的位置?

css - 具有全窗口滚动条高度的固定宽度框

javascript - 为事件监听器传递参数

javascript - Materialise 选项卡缩小了 fullcalendar

javascript - 如何使用jquery从url中删除index.php?

jquery - 如何调用jquery ajaxStart + ajaxComplete

iphone - UITableView使用CALayer + mask的滚动性能