开发者

Stopping increment at specific height

开发者 https://www.devze.com 2023-04-09 07:51 出处:网络
I am animating images within a logo in a slot-machine type o开发者_开发问答f animation. I need it to stop animating once it gets to the top of the image (and send a callback if possible).

I am animating images within a logo in a slot-machine type o开发者_开发问答f animation. I need it to stop animating once it gets to the top of the image (and send a callback if possible).

Currently, this is how I'm accomplishing the animation:

window.setInterval(function() {
    $('#title-1 img').animate({bottom : '-=60px'})
}, 5000);

Any ideas on how I would get it to stop, and to send the callback?


So I assume you have a sprite image containing multiple logos, you want them to slide each 5 seconds until you reach the last one, and then call the callback?

var cnt = 6,
    $img = $('#title-1 img'),
    i = 0;
function animate_logo(cb) {
    if (i < cnt) {
        $('#title-1 img').animate({bottom : '-=60px'});
        i += 1;
        setTimeout(function () {animate_logo(cb)}, 5000);
    }
    else {
        cb();
    }
}();


var interval = window.setInterval(function() {
    $('#title-1 img').animate({bottom : '-=60px'},
          function(){
                if(`some stop point`) clearInterval(interval);
          }
    );
}, 5000);


I would not suggest using a setInterval when dealing with animations due to the way newer browsers are making changes to the way setInterval and setTimeout work when the tab is not the active tab.

var $title1 = $("#title-1");
var $title1img = $title1.find('img');
function anim(){
  if ($title1.height() < parseInt($title1img.css("bottom"))) {
    setTimeout(function(){
      $title1img.animate({bottom : '-=60px'},anim);
    },5000);
  }
}
$title1img.animate({bottom : '-=60px'},anim);

Edit: another reason not to use setInterval to fire off animations is due to the reqeustAnimationFrame that was implemented in 1.6 and removed in 1.6.3, which will more than likely be added back in 1.7. If you write code now that will be compatible later, that's less maintenance you will have to do later if you end up being required to upgrade.

Here's a jsfiddle http://jsfiddle.net/czUnU/

Edit: function...

function animColumn(title,img){
  function anim(){
    if (title.height() < parseInt(img.css("bottom")) {
      setTimeout(function(){
        img.animate({bottom : '-=60px'},anim);
      },5000);
    }
  }
  img.animate({bottom : '-=60px'},anim);
}
animColumn($("#title-1"),$("#title-1 img"));
animColumn($("#title-2"),$("#title-2 img"));
animColumn($("#title-3"),$("#title-3 img"));

http://jsfiddle.net/czUnU/1/

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号