JavaScript动画setInterval / clearInterval

时间:2016-01-31 14:26:06

标签: javascript jquery-animate

我需要制作一个动画: 一个更宽的盒子,向右移动直到达到一个尺寸限制,然后再变薄。 (我试图给“更大”的间隔赋予更高的值,然后清除它并让“较小”的间隔继续播放并缩小它, 它实际上做了什么:它达到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);
 });

1 个答案:

答案 0 :(得分:0)

在“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 ...你可能想要停止一次宽度&lt; 0

为了使动画更流畅,我建议您查看requestAnimationFrame

相关问题