我想在诸如
之类的动画函数中旋转 div
$('div').animate({rotate: '30deg'},1000);
我发现了这个:
jQuery Patch: Animate CSS Rotation and Scale - zachstronaut
但我想知道是否有更正式的方法或至少不同的方法.
谢谢
解决方案
如果您愿意将 CSS3 与 jQuery 结合使用,也许这种方法可能对您有用:
HTML
<div id="click-me">Rotate</div> <div id="rotate-box"></div>
CSS
#rotate-box{ width:50px; height:50px; background:#222222; } @-moz-keyframes rotatebox /*--for firefox--*/{ from{ -moz-transform:rotate(0deg); } to{ -moz-transform:rotate(360deg); } } @-webkit-keyframes rotatebox /*--for webkit--*/{ from{ -webkit-transform:rotate(0deg); } to{ -webkit-transform:rotate(360deg); } } #click-me{ font-size:12px; cursor:pointer; padding:5px; background:#888888; }
假设有问题的元素应该在单击链接/div/按钮时旋转,您的 jQuery 将如下所示:
jQuery
$(document).ready(function(){ $('#click-me').click(function(){ $('#rotate-box').css({ //for firefox "-moz-animation-name":"rotatebox", "-moz-animation-duration":"0.8s", "-moz-animation-iteration-count":"1", "-moz-animation-fill-mode":"forwards", //for safari & chrome "-webkit-animation-name":"rotatebox", "-webkit-animation-duration":"0.8s", "-webkit-animation-iteration-count":"1", "-webkit-animation-fill-mode" : "forwards", }); }); });
因此,由于 jQuery 还不能在 .animate() 中支持旋转 (deg),因此我在 CSS3 中预先定义了动画关键帧并为该特定动画分配了标签或标识符,这有点欺骗了我.在本例中,该标签/标识符被定义为 rotatebox.
从这里开始,当点击可点击 div 时,jQuery 代码段将利用 .css() 并将必要的属性分配给可旋转元素.一旦分配了这些属性,就会有一个从元素到 CSS3 动画关键帧的桥梁,从而允许动画执行.您还可以通过更改 animation-duration 属性来控制动画的速度.
我个人认为只有在需要单击或鼠标滚动事件才能激活旋转时才需要此方法.如果旋转应该在文档加载后立即运行,那么单独使用 CSS3 就足够了.这同样适用于悬停事件是否应该激活旋转 - 您只需定义 CSS3 动画属性,将元素链接到元素伪类中的旋转动画.
我在这里的方法只是基于这样一个假设,即需要单击事件来激活旋转,或者需要 jQuery 以某种方式参与其中.我知道这种方法很乏味,所以如果有人有意见,请随时提出建议.另请注意,由于此方法涉及 CSS3,因此在 IE8 及以下版本上将无法正常工作.
其他解决方案
我觉得最简单的就是jsfiddle上的这个例子
$(function() { var $elie = $("img"), degree = 0, timer; rotate(); function rotate() { $elie.css({ WebkitTransform: 'rotate(' + degree + 'deg)'}); $elie.css({ '-moz-transform': 'rotate(' + degree + 'deg)'}); $elie.css('transform','rotate('+degree+'deg)'); timer = setTimeout(function() { ++degree; rotate(); },5); } $("input").toggle(function() { clearTimeout(timer); }, function() { rotate(); }); });
其他解决方案
QTransform 允许你旋转,倾斜,缩放和翻译,它可以跨浏览器工作.
下载并包含 QTransform.js 到您的 html.
<script src="js/qTransform.js"></script>
为您的 div 提供固定的高度-宽度并添加以下脚本:
$('#box4').delay(300).animate({rotate: '20deg'}, 500); $('#box5').delay(700).animate({rotate: '50deg'}, 500); $('#box6').delay(1200).animate({rotate: '80deg'}, 500);
where (box4, box5 & box6 是我的 div id).
delay(300), delay(700) & delay(1200) 在 300、500 和 1200 毫秒后开始动画.最后的 500 是动画的持续时间.
如果你想手动提供旋转角度,你可以这样做:
取变量中的角度.例如
var degAngle = 60;
并将其添加到脚本中,如
$('#box4').delay(300).animate({rotate: degAngle+'deg'}, 500);
您还可以提供多种效果,例如缩放和旋转.例如,
$('#box4').delay(300).animate({scale: '1.5', rotate: '20deg'}, 500);
为什么选择 QTransform?
到目前为止,jQuery 不支持 CSS3 动画.这个插件可以帮助你完成你的目标.