使用jQuery是否可以旋转一个div?我可以旋转图片,但无法旋转div;有没有解决方案?
使用jQuery是否可以旋转一个div?我可以旋转图片,但无法旋转div;有没有解决方案?
编辑:已更新至jQuery 1.8
自jQuery 1.8起,浏览器特定的转换将被自动添加。jsFiddle演示
var rotation = 0;
jQuery.fn.rotate = function(degrees) {
$(this).css({'transform' : 'rotate('+ degrees +'deg)'});
return $(this);
};
$('.rotate').click(function() {
rotation += 5;
$(this).rotate(rotation);
});
编辑:添加了代码,将其变成jQuery函数。
对于那些不想继续阅读的人,这里是代码。如需更多详细信息和示例,请继续阅读。jsFiddle演示。
var rotation = 0;
jQuery.fn.rotate = function(degrees) {
$(this).css({'-webkit-transform' : 'rotate('+ degrees +'deg)',
'-moz-transform' : 'rotate('+ degrees +'deg)',
'-ms-transform' : 'rotate('+ degrees +'deg)',
'transform' : 'rotate('+ degrees +'deg)'});
return $(this);
};
$('.rotate').click(function() {
rotation += 5;
$(this).rotate(rotation);
});
编辑:本文评论区有一条提到 jQuery Multirotation 的评论。这个 jQuery 插件可以在支持 IE8 的浏览器中实现上述功能。如果你想要最大的兼容性或更多选项,可能值得使用。但对于最小的开销,建议使用上述函数。它可以在 IE9+、Chrome、Firefox、Opera 和许多其他浏览器中使用。
Bobby... 这是给那些真正想用 JavaScript 实现旋转的人看的。这可能需要在 JavaScript 回调函数中进行旋转。
这里有一个 jsFiddle。
如果你想要按照自定义的时间间隔旋转,可以使用 jQuery 手动设置 css 样式,而不是添加类名。像 这样!我在答案底部包含了这两种 jQuery 选项。
HTML
<div class="rotate">
<h1>Rotatey text</h1>
</div>
CSS
/* Totally for style */
.rotate {
background: #F02311;
color: #FFF;
width: 200px;
height: 200px;
text-align: center;
font: normal 1em Arial;
position: relative;
top: 50px;
left: 50px;
}
/* The real code */
.rotated {
-webkit-transform: rotate(45deg); /* Chrome, Safari 3.1+ */
-moz-transform: rotate(45deg); /* Firefox 3.5-15 */
-ms-transform: rotate(45deg); /* IE 9 */
-o-transform: rotate(45deg); /* Opera 10.50-12.00 */
transform: rotate(45deg); /* Firefox 16+, IE 10+, Opera 12.10+ */
}
jQuery
请确保这些被包裹在$(document).ready里面。
$('.rotate').click(function() {
$(this).toggleClass('rotated');
});
自定义间隔时间。var rotation = 0;
$('.rotate').click(function() {
rotation += 5;
$(this).css({'-webkit-transform' : 'rotate('+ rotation +'deg)',
'-moz-transform' : 'rotate('+ rotation +'deg)',
'-ms-transform' : 'rotate('+ rotation +'deg)',
'transform' : 'rotate('+ rotation +'deg)'});
});
$.fn.rotate
替换定义中的jQuery.fn.rotate
- 它们执行相同的操作,但前者更加简洁。 - clearlight