Stopping jQuery from doing its thing?

2019-02-18 23:11发布

I have this code.

$(document).ready(function() {
$('#box').hide();
$(window).bind('scroll', function(){
    if($(this).scrollTop() > 200) {
        $("#box").fadeIn(300);
    }
    else {
    $("#box").fadeOut(300);
    }
});
});

So when I scroll down 200px it will make a div appear. When I scroll back up, it will disappear. This is fine, until I do it a lot.

If I scroll up and down like a nutter the div keeps fading in and out even after I stop. This isn't related to just this instance, it's happened a lot in the past and I've always wanted to know how to fix it (by making it stop as soon as I have, without doing it for everytime I scrolled up and down).

Is that possible?

5条回答
手持菜刀,她持情操
2楼-- · 2019-02-18 23:44

Use the stopdocs function

You simply need to call $('#box').stop(true,true).fadeIn(300); and $('#box').stop(true,true).fadeOut(300); respectively

查看更多
干净又极端
3楼-- · 2019-02-18 23:47

Try using stop() before more animations are queued:

$(document).ready(function() {
    $('#box').hide();
    $(window).bind('scroll', function(){
        if($(this).scrollTop() > 200) {
            $("#box").stop().fadeIn(300);
        }
        else {
            $("#box").stop().fadeOut(300);
        }
    });
});

See the documentation here: http://api.jquery.com/stop/

查看更多
放荡不羁爱自由
4楼-- · 2019-02-18 23:57

You have to add stop function to your queue like this: $('#box').stop(true).fadeOut(300);

function stop() description: see here

查看更多
爷、活的狠高调
5楼-- · 2019-02-18 23:59

.clearQueue() worked much better than .stop()

查看更多
对你真心纯属浪费
6楼-- · 2019-02-19 00:00

jQuery has a stop() method - http://api.jquery.com/stop/

This article describes how to use it, seems to be exactly what you're looking for: http://www.learningjquery.com/2009/01/quick-tip-prevent-animation-queue-buildup

查看更多
登录 后发表回答