在用户滚动时阻止功能运行

时间:2012-12-13 20:15:49

标签: javascript jquery

我该怎么办?

myfunction () {

    if (notscrolling) {

        // do stuff

    }
}

这是我能找到的最佳解决方案:

它获取当前滚动位置,然后在5毫秒后再次获取它。如果数字相同,则页面不滚动!无需全局变量。

myfunction () {

    var a = $(document).scrollTop();

    setTimeout(function() { 
        var b = $(document).scrollTop();

            if (a === b) {

                // do stuff here cuz its not scrolling :) !!!!

            }
    }, 5);

}

3 个答案:

答案 0 :(得分:1)

结帐http://james.padolsey.com/javascript/special-scroll-events-for-jquery/ 用于scrollstart和scrollstop事件。

使用这些事件设置全局变量scrolling并在myfunction

中进行检查

答案 1 :(得分:1)

我认为这篇文章很符合您的要求: How to trigger ajax request on scroll stop?

你想要达到的目标是“scrollStop”之类的东西。

答案 2 :(得分:0)

在窗口滚动事件上,将全局滚动变量设置为true或false,然后在scroll事件中设置setTimeout,在x miliseconds之后将其设置回默认值。然后,您可以使用该全局变量的值来确定窗口是否在滚动。

window.scrolling = false;
var timer;

$(window).on('scroll',function(){
    window.scrolling = true;
    clearTimeout(timer);
    timer = setTimeout(function(){
        window.scrolling = false;
        $(window).trigger("scrollend");
    },100);
});

function myfunction() {
    if (!window.scrolling) {
        alert("Window is not scrolling.");
    }
}

甚至更好,不要使用全局范围。

(function(){
    var timer, scrolling = false;

    $(window).on('scroll',function(){
        scrolling = true;
        clearTimeout(timer);
        timer = setTimeout(function(){
            scrolling = false;
            $(window).trigger("scrollend");
        },100);
    });

    function myfunction() {
        if (!scrolling) {
            alert("Window is not scrolling.");
        }
    }
})();
相关问题