Jquery Animate - 使元素反弹一次

时间:2014-08-27 13:16:56

标签: javascript jquery dom

我有一个方框.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添加到第二个动画,但它仍然没有用。任何人都可以告诉我如何让元素跳转一次而不是重复跳转?

在这里小提琴:http://jsfiddle.net/duwtbux0/

4 个答案:

答案 0 :(得分:3)

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

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/

答案 1 :(得分:3)

如果您愿意,还有另一种可能性:

$(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/

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

答案 2 :(得分:0)

如果你想让盒子只弹出onces,你需要取消绑定文件上的keydown监听器。

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

队列属性并不意味着你想做什么。该队列仅用于告诉jquery您是要立即执行动画还是在最后一个动画完成后执行动画。

答案 3 :(得分:0)

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

这对我来说很好!!