JavaScript setInterval不会降低变量值

时间:2014-01-01 03:35:00

标签: javascript jquery html css3 setinterval

<div id="rope" style="-webkit-transform: rotate(-25deg);-webkit-transition:all 1s;position:absolute;top:50px;left:50px;">

<div style="position:absolute;top:25px;left:25px;width:5px;background-color:#c3c3c3;height:100px;"></div>
<div style="position:absolute;top:100px;left:15px;"><img src="http://images1.wikia.nocookie.net/__cb20111028025351/cuttherope/images/1/1c/Candy.png" style="height:30px;"></div>

</div>

<script>
count = 25;
setInterval(function(){

document.getElementById("rope").style.webkitTransform="rotate("+count+"deg)";

count = count*-1;

count = count-1;

} ,'1000');
</script>

测试一下,有一个问题:它永远不会减少来回旋转的数量。

需要帮助,因为这应该很容易修复,但是setInterval总是设法让我感到困惑,特别是处理添加到变量:\

我希望每次旋转更少,更少,所以...非常感谢你的帮助:)

3 个答案:

答案 0 :(得分:1)

你的问题是伯爵在-26到25之间反弹。

每个时间间隔:

  1. count = -count - 1 = -26。
  2. count = - ( - 26) - 1 = 26 - 1 = 25.
  3. count = - (25) - 1 = -26。
  4. count = ...
  5. 所以伯爵会在这两个值之间反弹; -26和25.

    根据你的评论,只需通过if-test(即if(count&lt; 0){...})来实现。

答案 1 :(得分:0)

您的count = count*-1;count = count-1;只会重复-26和25的模式。

答案 2 :(得分:0)

解决方案JS

count = 25;
intvar=setInterval(function(){
    document.getElementById("rope").style.webkitTransform = "rotate("+count+"deg)";

    count = count*-1;
    if(count>0)
    {
        count = count-4;// Change 4 to any small integer to keep the difference of angular travel(in degree) each time as small as possible and keep it big if you want a greater difference each time in the angular travel.
        if(count<0)
            clearInterval(intvar);
        console.log(count);
    }
} ,'1000');

<强> JSFIDDLE