返回隐藏元素时的JS动画循环

JS animation loop when returning to hide element

我有一个元素,我对其进行动画处理以在屏幕上移动。从 left:-100pxleft:screen-width。我循环了 4 次。

当将元素返回到其原始位置 left:-100px 时,我真的不希望看到它在屏幕上移动(从右到左)快。

我尝试通过 .hide() 隐藏元素然后在一段时间后显示它(以便它有时间移回其初始位置)来做到这一点。但这 工作:

$('.snake-image').hide();
$('.snake-image').css('top', height / 2).css('left', currentPos);
setTimeout(function(){$('.snake-image').show();},1000);

代码:

$('body').append('<a href="#"><img src="https://dl.dropboxusercontent.com/u/48552248/projects/covve/website/2015/public/images/snake.png" class="snake-image" style="position:absolute;top:0;" />');

function goRight(currentPos) {
  $('.snake-image').animate({
    left: currentPos
  }, 100);
}

function moveSnake() {
  while (currentPos <= width) {
    goRight(currentPos);
    currentPos += 20;
    console.log(width + " x " + currentPos);
  }
}

var currentPos,
    height = $(window).height(),
    width = $(window).width(),
    i = 4;

var intervalID = setInterval(function(){
  if (i > 0){
    currentPos = -100;
    $('.snake-image').hide();
    $('.snake-image').css('top', height / 2).css('left', currentPos);
    setTimeout(function(){$('.snake-image').show();},1000);
    moveSnake();
    i--;
    console.log('Interval 1');
  } else {
    clearInterval(intervalID);
  }
}, 100);

演示:http://jsfiddle.net/m0epjLym/

你可以这样做:

$('.snake-image').animate({'opacity': 0}, 0);
$('.snake-image').animate({'top': height / 2}, 0).animate({'left': currentPos}, 0).delay(1000).animate({'opacity': 1}, 0);

延迟功能仅对动画队列中的项目起作用。

Fiddle: http://jsfiddle.net/y995cts3/3/

你可以使用动画 callback 在动画结束时触发,您可以将项目移回原始位置,然后再次调用动画

Fiddle:http://jsfiddle.net/xgknu376/