0

我一直在试图弄清楚如何让这个脚本在点击时无限旋转图像,然后在你再次点击它时停止它。任何人都可以修改它以使其做到这一点吗?

$(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

4 回答 4

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!
});
于 2013-05-20T02:31:45.487 回答
0

尝试使用setIntervalandclearInterval而不是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

于 2013-05-20T02:22:46.770 回答
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));
        }
    });

});

演示:小提琴

于 2013-05-20T02:58:33.357 回答
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);
    });
});
于 2013-05-20T03:04:00.733 回答