Jquery动画-使元素只反弹一次
Jquery Animate - Making the element bounce just once
我有一个盒子.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);
}
}
});
这对我来说很好!!
相关文章:
- jQuery:试图让动画每3秒发生一次,但没有成功
- jQuery+Animate.css动画只工作一次,动画不会重置
- HTML画布-使动画一次发生一个,而不是同时发生多个
- 为jquery设置动画,一次设置一个对象
- 菜单在每单击一次时切换不同的动画
- jQuery - 在一个会话中仅运行一次动画
- 如何一次为多个事物设置动画
- CSS 动画只工作一次
- 如何阻止 CSS3 动画在播放一次后运行并调用新动画
- 如何让动画在视口中启动一次
- 一次对一个进度条进行动画处理
- jQuery 动画运行一次
- 动画 GIF 背景仅显示一次
- 为什么单击时的关键帧动画只触发一次
- 每次单击一次迭代两个数组并制作动画
- 在滚动时制作一次动画
- JavaScript动画,图像动画只动画一次
- 每3秒重复一次动画
- 在单击按钮时使用同位素对数据进行排序,目前只运行一次动画
- ScrollMagic Tween:向前只播放一次动画