Javascript-单击可无限旋转图像,再次单击可停止
我一直在试图弄清楚如何让这个脚本在单击时无限旋转图像,然后在再次单击时停止它。有人能修改它让它这样做吗Javascript-单击可无限旋转图像,再次单击可停止,javascript,jquery,html,rotatetransform,Javascript,Jquery,Html,Rotatetransform,我一直在试图弄清楚如何让这个脚本在单击时无限旋转图像,然后在再次单击时停止它。有人能修改它让它这样做吗 $(function() { var $rota = $('.spin'), degree = 0, timer; function rotate() { $rota.css({ transform: 'rotate(' + degree + 'deg)'}); // timeout increase
$(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!
});
尝试使用
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上读取数据,您可以创建一个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!
});
试一试
演示:您尝试了哪些浏览器?您可能需要供应商前缀。。。
$(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);
});
});