简体   繁体   中英

JS animation loop when returning to hide element

I have an element which I animate to move across the screen. From left:-100px to left:screen-width . I loop this 4 times.

When returning the element back to its original position left:-100px , I don't want it to be seen moving across the screen ( from right to left ) really fast.

I tried to do it by hiding the element with .hide() and then showing it after a while (so that it has time to move back to its initial position). But this doesn't work:

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

Code:

$('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);

Demo: http://jsfiddle.net/m0epjLym/

You can do this:

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

The delay function will only work on items that are in the animation queue.

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

you could use the animate callback triggered at the end of the animation, you can move your item back in the origina position and then call again the animation

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM