Javascript - 单击无限旋转图像,然后再次单击停止

时间:2013-05-20 02:14:43

标签: javascript jquery html rotatetransform

我一直在试图弄清楚如何让这个脚本无限地旋转图像然后再次单击它时停止它。任何人都可以修改它来实现它吗?

$(function() {

    var $rota = $('.spin'),
        degree = 0,
        timer;

    function rotate() {    
        $rota.css({ transform: 'rotate(' + degree + 'deg)'});
        // timeout increase degrees:
        timer = setTimeout(function() {
            ++degree;
            rotate(); // loop it
        },5);
    }

    rotate();    // run it!

});

4 个答案:

答案 0 :(得分:1)

您可以创建一个bool来确定是否已单击该元素,在单击时更改它并在发生单击时停止该过程。

$(function() {

    var $rota = $('.spin'),
        degree = 0,
        clicked = false,
        timer;

    $rota.on('click', function() { clicked = true; return false; } );

    function rotate() { 
        if ( clicked )   
            $rota.css({ transform: 'rotate(' + degree + 'deg)'});
            // timeout increase degrees:
            timer = setTimeout(function() {
               ++degree;
               rotate(); // loop it
            },5);
        }

        rotate();    // run it!
});

答案 1 :(得分:0)

尝试使用setIntervalclearInterval代替setTimeout

function rotate() {    
    $rota.css({ transform: 'rotate(' + degree + 'deg)'});
    ++degree;
}

var loop;
$rota.click(function() { 
    if(loop) {
         clearInterval(loop);
         loop = false;
    }
    else {
        loop = setInterval(rotate, 5);
    }
});

您可以阅读setInterval here

答案 2 :(得分:0)

尝试

$(function() {

    var $rota = $('.spin')

    $rota.click(function(){
        var $this = $(this);

        if($this.data('rotating')){
            clearInterval($this.data('rotating'));
            $this.data('rotating', false)
        } else {
            $this.data('rotating', setInterval(function(){
                var degree = $this.data('degree') || 0;
                $this.css({ transform: 'rotate(' + degree + 'deg)'});
                $this.data('degree', ++degree)
            }, 5));
        }
    });

});

演示:Fiddle

答案 3 :(得分:0)

$(function() {
    var $rota = $('img'), degree = 0, timer, enabled;
    var rotate = function() {
        timer = setInterval(function() {
            ++degree;
            $rota.css({
              transform: 'rotate(' + degree + 'deg)'
            });
        },5);
    };
    $rota.on('click', function(){
       enabled = !enabled;
       enabled ? rotate() : clearInterval(timer);
    });
});