如果您愿意将 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() 中支持 rotate(deg),所以我通过在 CSS3 中预定义动画关键帧并为该特定动画分配标签或标识符有点作弊。在此示例中,该标签/标识符定义为 rotatebox。
从这里开始发生的事情是,当点击可点击的 div 时,jQuery sn-p 将利用 .css() 并将必要的属性分配给可旋转元素。在分配这些属性的那一刻,将有一个从元素到 CSS3 动画关键帧的桥梁,从而允许动画执行。您还可以通过更改 animation-duration 属性来控制动画的速度。
我个人认为只有在需要单击或鼠标滚动事件来激活旋转时才需要此方法。如果旋转应该在文档加载后立即运行,那么单独使用 CSS3 就足够了。如果悬停事件应该激活旋转,这同样适用 - 您只需在元素的伪类中定义将元素链接到旋转动画的 CSS3 动画属性。
我的方法只是基于这样的假设,即激活旋转需要单击事件,或者需要 jQuery 以某种方式参与其中。我知道这种方法非常乏味,所以如果有人有意见,请随时提出建议。另请注意,由于此方法涉及 CSS3,因此在 IE8 及以下版本中无法正常工作。