jQuery - how to treat scroll as single event?

2020-07-12 05:36发布

When I bind function to scroll and scroll mousewheel once, the function runs seven or eight times. I want it to run only once when I scroll the mousewheel once, is this possible? I use this code:

$(document).ready(function () {
    $(window).bind('scroll', function() {
        alert("Scroll.");          
    }   
    });
});

标签: jquery scroll
5条回答
老娘就宠你
2楼-- · 2020-07-12 05:37

You can use throttle function from jQuery throttle debounce plugin.

$(function() {
    $(window).bind('scroll', $.throttle(100, function() {
        console.log('scroll');
    }));
});
查看更多
成全新的幸福
3楼-- · 2020-07-12 05:42

just a variation of Aruns answer:

Similar approach,just that the event get's fired immediately and is then prevented to be handled again for an interval of time. So that you wouldn't have to wait before handling the event.

$(document).ready(function () {
    var locked = false
        , timeout;

    $(window).bind('scroll', function() {
        //do nothing if still locked
        if(true === locked){
            return false;
        }
        //lock
        locked = true;

        //do something if not locked
        alert('scroll!')

        clearTimeout(timeout)
        timeout = setTimeout(function(){
            //unlock
            locked = false;         
        }, 1000)
    });
});
查看更多
冷血范
4楼-- · 2020-07-12 05:42

If by "once" you mean, once-per-page-load, you could unbind the event in the listener with the off() method. http://api.jquery.com/off/

There's also the possibility of namespacing events like:

scroll.namespace is still the same event, but you can unbind it specifically.

$(document).ready(function () {
    $(window).on('scroll.myEvent', function() {
        $(window).off('scroll.myEvent');
        alert("Scroll.");          
    }   
    });
});
查看更多
祖国的老花朵
5楼-- · 2020-07-12 05:55

Try

$(document).ready(function () {
    var timerId;
    $(window).bind('scroll', function() {
        clearTimeout(timerId)
        timerId = setTimeout(function(){
            alert("Scroll.");          
        }, 200)
    });
});

Demo: Fiddle

查看更多
Evening l夕情丶
6楼-- · 2020-07-12 05:58

If you want to detect scrolling only once, use this:

$(function () {
    var done = false;
    $(window).bind('scroll', function() {
       if (!done){
           alert("Scroll.");
           done = true;
       }
   });
});

but if you want to detect every scroll event, try something like the answer 4

查看更多
登录 后发表回答