JavaScript animation setInterval / clearInterval

JavaScript animation setInterval / clearInterval

本文关键字:clearInterval setInterval animation JavaScript      更新时间:2023-09-26

我需要制作一个动画:一个变宽并向右移动的盒子,直到达到大小限制,然后再次变薄。(我试图为"较大"间隔提供更高的值,然后清除它并让"较小"间隔继续播放并缩小它,它实际做什么:它达到200px,然后重复地以5px的速度变大变小,并继续向右移动(

 function animatesmall(name, dist, time) {
     $(name).animate({
         left: dist
     }, time);
     $(name).css({
         width: numberup
     });
     numberup = numberup - 5;
 }
 var numberup = 1;
 function animatebig(name, dist, time) {
     if (numberup < 200) {
         $(name).animate({
             left: dist
         }, time);
         $(name).css({
             width: numberup
         });
         numberup = numberup + 10;
     } else {
         clearInterval(bigger);
     }
 }
 $(function () {
     var bigger = setInterval(function () {
         animatebig('.box1', "+=1", 100)
     }, 100);
     var smaller = setInterval(function () {
         animatesmall('.box1', "+=1", 100)
     }, 100);
 });

直到"numberup"达到200,你实际上是在加10,从宽度中减去5

当它达到 200 以上时,你只减去 5

然后,由于"更大"没有在$(function()范围之外定义,因此仍然调用animatebig,因此盒子的大小会波动

像这样编写代码似乎更有效率

$(function () {
    var numberup = 1;
    var delta = 5;
    function animate(name, dist, time) {
        if (delta > 0 && numberup >= 200) {
            delta = -5;
        }
        else if (numberup < 0) {
            clearInterval(timer);
        }
        $(name).animate({
            left: dist
        }, time);
        $(name).css({
            width: numberup
        });
        numberup += delta;
    }
    var timer = setInterval(function () {
        animate('.box1', "+=1", 100)
    }, 100);
});

这有一个单一的区间,增长 5,然后收缩 5 ...您可能希望停止一次宽度<0

为了获得更流畅的动画,我建议查看requestAnimationFrame