如何使用jQuery旋转div

是否有可能使用jQuery旋转div? 我可以旋转图像,但不能旋转div; 有没有解决scheme?

编辑:更新为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); }); 

编辑:添加代码,使其成为一个jQueryfunction。

对于那些不想进一步阅读的人,在这里,你去。 有关更多详细信息和示例,请继续阅读。 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); }); 

编辑:这个post上的评论之一提到jQuery Multirotation 。 jQuery的这个插件本质上支持IE8执行上述function。 如果你想要最大的兼容性或更多的select,这可能是值得使用的。 但是为了尽量减less开销,我build议上述function。 它将工作IE9 +,Chrome浏览器,Firefox,Opera等等。


Bobby …这是给那些真正想在javascript中做的人。 这可能是需要在JavaScriptcallback旋转。

这是一个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)'}); });