开发者

Ignore if it's already fading

开发者 https://www.devze.com 2023-03-27 02:09 出处:网络
<p onclick=\"fade()\">Click me</p> <p id=\"myID\">Text</p> <script> function fade() {
<p onclick="fade()">Click me</p>
<p id="myID">Text</p>

<script>
function fade() {
    $(开发者_如何学Python'#myID').fadeToggle('slow');  
}
</script>

If I spam "Click me", I mean if I click fast say ten times, "Text" continues to fade in and out until it has finished my ten clicks.

Is there anything I can do so that it ignores a click if it's already fading?


If ($("#myID").not(":animated"))
{
 $('#myID').fadeToggle('slow');  
}


Use http://api.jquery.com/queue/ to find out whether there are any effects being performed on the element already. Something like (not tested):

if ($('#myID').queue().length == 0) $('#myID').fadeToggle('slow');

If you do want to stop the current effect and perform the toggle, use .stop() instead.


source: jQuery animation: Ignore double click

<p onclick="fade()">Click me</p>
<p id="myID">Text</p>

<script>
function fade() {
    if( !$('#myID').is(':animated') ) {
    $('#myID').fadeToggle('slow');  
    }
}
</script>

jsfiddle


There are two approaches here, subtly different from one another.


Approach 1

function fade() {
    var $obj = $('#myID');
    if (!$obj.is(':animated')) {
        $obj.fadeToggle('slow');
    }
}

This is what you asked for. A new fade will only be queued if one isn't already going on.

The downside here is that we check for any animation (not just toggle fades), but you could expand this if really necessary (e.g. see Mike Thomsen's answer).

Live demo.


Approach 2

Instead of blocking new fades, you could cancel the current ones:

function fade() {
    $('#myID').stop(true, true).fadeToggle('slow');
}

The downside here is that the new animation starts immediately and this looks rather jarring.

The second parameter to .stop must be true (or you'll lose the element's original full opacity forever), and flipping the first one does not fix the downside of this approach.

Live demo.


function fade() {
    var that = this;
    if (!$(this).attr('fading')) {
        $(this).attr('fading', true);
        $('#myID').fadeToggle('slow', function() {
            $(that).removeAttr('fading');
        });
    }
}


This works in my testing:

$('.fade').click(function() {
    $('#myID').stop(true, true).fadeToggle('slow');

});

See jsfiddle

The idea to add paramaters to stop() came from this post: jQuery fadeToggle if currently animated, ignore further input

0

精彩评论

暂无评论...
验证码 换一张
取 消