Jquery动画-使元素只反弹一次

Jquery Animate - Making the element bounce just once

本文关键字:一次 动画 元素 Jquery      更新时间:2023-09-26

我有一个盒子.child。我想让这个盒子跳起来,然后当按下向上键时回到原来的位置。我有以下脚本:

$(document).on('keydown', function( e ){
    if ( e.keyCode === 38 ) {
        $('.child').animate({ 
            'bottom' : '50px'
        }, 250).animate({
            'bottom' : '0px' 
        }, 250);
    }
});

现在,当按下向上键时,它确实会使元素反弹。但是,如果我一次又一次地按下向上键,即使在没有按下键的情况下,它也会让盒子一跳再跳。现在我知道了queue,所以我尝试了以下操作:

$(document).on('keydown', function( e ){
    if ( e.keyCode === 38 ) {
        $('.child').animate({ 
            'bottom' : '50px'
        }, {
            duration: 250,
            queue: false
        }).animate({
            'bottom' : '0px' 
        }, {
            duration: 250,
            queue: false
        });
    }
});

但它也没有像预期的那样起作用。然后我想只将queue : false添加到第二个动画中,但仍然没有成功。有人能告诉我如何让元素跳一次而不是重复跳吗?

Fiddle here:http://jsfiddle.net/duwtbux0/

只需添加某种标志即可阻止接受输入。

var acceptingInput = true;
$(document).on('keydown', function( e ){
    if(acceptingInput){
        if ( e.keyCode === 38 ) {
            acceptingInput = false;
            $('.child').animate({ 
                'bottom' : '50px'
            }, 250).animate({
                'bottom' : '0px' 
            }, 250, function() {
                acceptingInput = true;
            });
        }
    }
});

小提琴:http://jsfiddle.net/duwtbux0/2/

如果你愿意,这里还有另一种可能性:

$(document).on('keydown', function( e ){
    if ( e.keyCode === 38 ) {
        $('.child').stop(1,0).animate({ 
            'bottom' : '50px'
        }, 250).animate({
            'bottom' : '0px' 
        }, 250);
    }
});

只要你反复按下向上键,添加.stop(1,0)将使区块保持在空中,也将停止排队。

http://jsfiddle.net/duwtbux0/5/

这可能不是你想要的,但值得一提。

如果你想让盒子只反弹一次,你需要解除文档上keydown监听器的绑定。

$(document).on('keydown.bounce', function( e ){
    if ( e.keyCode === 38 ) {
        $('.child').animate({ 
            'bottom' : '50px'
        }, 250).animate({
            'bottom' : '0px' 
        }, 250);
        $(document).unbind('.bounce');
    }
});

队列属性并不意味着要执行您想要的操作。该队列仅用于告诉jquery您是想立即执行动画还是在上一个动画完成后执行。

$(document).on('keydown', function( e ){
    if($('.child').css('bottom') === '0px'){
    if ( e.keyCode === 38 ) {
        $('.child').animate({ 
            'bottom' : '50px'
        }, 250).animate({
            'bottom' : '0px' 
        }, 250);
    }
    }
});

这对我来说很好!!