开发者

trying to rotate a div element with jQuery controlling css3 transform command

开发者 https://www.devze.com 2023-02-22 03:09 出处:网络
Basically, what I\'ve got going is a timer that counts every half second and on that it should update the degree and the div should be rotated to the new degree. The end result of this should (theoret

Basically, what I've got going is a timer that counts every half second and on that it should update the degree and the div should be rotated to the new degree. The end result of this should (theoretically) be a somewhat smooth constantly rotating div.

Sadly, it goes as far as rotating it 1 degree and then the degree is not updated again even though according to the console log the number is still counting up.

Any suggestions?

setInterval(func开发者_如何转开发tion()
    {
        var i = 0;
            i++;

        $('#nav').css({'-webkit-transform' : 'rotate(' + i + 'deg)'});

        console.log(i);
    }
    , 1000);

Thanks!


Every time that function is called you are setting the variable i back to zero:

var i = 0;

...then adding one.

i++;

So it will always be "1". You need to store that value somewhere else, OR parse it from the css attribute each time, then add one. Here is the former solution as an example:

var rotate_degrees = 0;

setInterval(function()
{
    rotate_degrees++;
    $('#nav').css({'-webkit-transform' : 'rotate(' + rotate_degrees + 'deg)'});
    console.log(rotate_degrees);
}
, 1000);

What makes the difference is declaring the varialbe outside the scope of the function as opposed to inside.


The variable i is local to the function so it will always be 1. Change the name to something like rotationCount and declare it globally (e.g. outside of all functions)

Also, you will want to do modula 360 arithmetic.

0

精彩评论

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

关注公众号