2013-05-20 2 views
0

Я пытался выяснить, как заставить этот скрипт бесконечно поворачивать изображение, а затем останавливать его, когда вы нажмете его снова. Может ли кто-нибудь изменить его, чтобы заставить его это сделать?Javascript - Нажмите, чтобы повернуть изображение бесконечно и нажмите еще раз, чтобы остановить

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

}); 
+1

Какие браузеры вы пробовали? Вам могут потребоваться префиксы поставщика ... – elclanrs

ответ

0

Попробуйте использовать setInterval и clearInterval вместо 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

1

вы можете создать логическое значение, чтобы определить, является ли элемент нажимали, изменить его нажмите и остановите процесс, если щелчок произошел.

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

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); 
    }); 
}); 
Смежные вопросы