点击图像无限旋转,再次点击停止
Javascript - Click to rotate image infinitely and click again to stop
我一直在努力弄清楚如何让这个脚本无限旋转图像,然后在您再次单击它时停止它。有人能修改它让它这样做吗?
$(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!
});
尝试使用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
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);
});
});
相关文章:
- 全屏背景图像+旋转图像
- 每次单击JQuery时旋转图像
- 旋转和取消旋转图像单击与 javascript
- SVG具有旋转图像的低性能
- 旋转图像,使其看起来像在旋转
- 向下滑动时旋转图像
- 滚动时旋转图像
- 使用 kineticjs 如何就地旋转图像对象
- 将变量 javascript 添加到用于旋转图像的链接中
- 旋转图像w/jQuery..但是调整大小不起作用
- 使用 JQueryRotate 逆时针旋转图像
- 在不旋转元素尺寸的情况下旋转图像
- 如何旋转图像并保存图像
- 在HTML5画布中,有没有办法以不同的角度旋转图像
- 在 html5 画布中用鼠标旋转图像
- 如何在时间变化时旋转图像
- 在横幅中水平对齐图像和 JavaScript 旋转图像
- 在 HTML 中旋转图像
- 如何使用 JavaScript 在 Web 中显示之前旋转图像
- jQuery - 旋转图像