点击图像无限旋转,再次点击停止

Javascript - Click to rotate image infinitely and click again to stop

本文关键字:旋转 图像 无限      更新时间:2023-09-26

我一直在努力弄清楚如何让这个脚本无限旋转图像,然后在您再次单击它时停止它。有人能修改它让它这样做吗?

$(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!
});

您可以创建一个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!
});

尝试使用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

Try

$(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));
        }
    });
});

演示:小提琴

$(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);
    });
});