缩短jQuery动画功能,并在键盘上恢复到“开始”

Cut jQuery Animate Function Short and Revert to Start on Keypress

本文关键字:恢复 开始 键盘 动画 jQuery 功能 缩短      更新时间:2023-09-26

我有一个简单的丢球动画,我正在使用jQuery animate函数。球从bottom: 600开始下落,直到到达地面,即bottom: 90

function ballbounce() {
  $('.football').animate({
    'bottom': 90
  }, bouncetime, 'easeOutBounce', function() {
  });
}

当按下空格键时,我想缩短下降的动画,让球再次上升。我尝试通过检测按键,获得球的当前bottom值,在该值上添加300px,然后将其设置为球上的新bottom值。但我希望下降的动画从那一点开始恢复。

$(document).keydown(function(e) {
  switch(e.which) {
    case 32: // spacebar
      var ballOffset = $('.football').offset();
      var currentBallPosition  = $(window).height() - ballOffset.top - $('.football').height();
      var newBallPosition = currentBallPosition + 300;
      $('.football').css("bottom", newBallPosition);
    break;
    default: return; // exit this handler for other keys
  }
  e.preventDefault(); // prevent the default action
});

我不能让它工作,我不确定哪里出了问题。只有在动画完成后按空格键时,才会更新球的bottom

这是一个基本的足球比赛。所以球掉了下来,你按下空格键将球再次踢回空中。这是一个好的解决方案吗?

我会在元素上调用.stop(),然后将其重置到原始位置。您可以在动画之前将原始位置存储为元素本身的数据属性,然后使用该属性稍后重置它,如下所示:

function ballbounce(selector,bouncetime) {
  var $ball= $(selector);  
  $ball.data('original-top',$ball.position().top )
  $ball.animate({ top: '+550px'}, bouncetime, "easeOutBounce", function() {
      //animation complete
  });
  return $ball;  
}
var $ballReference=ballbounce('.football',5000);
$(document).keydown(function(e) {
  switch(e.which) {
    case 32: // spacebar
          $ballReference.stop().css({top:$ballReference.data('original-top')});
    break;
    default: return; // exit this handler for other keys
  }
  e.preventDefault(); // prevent the default action
});
.football{
    width:100px;
    height:100px;
    background-color:#ccc;
    position:absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.3/jquery-ui.min.js"></script>
<div class="football"></div>