【发布时间】:2016-01-06 14:47:26
【问题描述】:
我需要创建一个旋转动画。单击事件将元素旋转 180° 以指向下方。另一个点击事件将同一元素旋转回 0° 以指向上方。
我将animation-fill-mode 设置为forwards 以保留最后一个关键帧状态。但它似乎没有工作。所有视觉元素都重置为默认状态。
任何想法我可能做错了什么?
我的 Codepen:http://codepen.io/simspace-dev/pen/RrpGmP
我的代码:
(function() {
$('#btnb').on('click', function(e) {
return $('.box').addClass('spin-counter-clockwise');
});
$('#btnf').on('click', function(e) {
return $('.box').addClass('spin-clockwise');
});
$('.box').on('webkitAnimationEnd', function(e) {
return $(e.target).removeClass('spin-counter-clockwise').removeClass('spin-clockwise');
});
}.call(this));
.box {
background: red;
position: relative;
width: 176px;
height: 176px;
margin: 40px auto;
text-align: center;
}
.box .top {
background: green;
position: absolute;
top: 0;
width: 100%;
height: 28px;
}
.box .bottom {
background: purple;
position: absolute;
bottom: 0;
width: 100%;
height: 28px;
}
.box .caret {
color: white;
font-size: 88px;
position: absolute;
top: 42px;
left: 50px;
}
.spin-clockwise {
-moz-animation: spin 2s;
-webkit-animation: spin 2s;
-moz-animation-fill-mode: forwards;
-webkit-animation-fill-mode: forwards;
}
.spin-counter-clockwise {
-moz-animation: spin 2s reverse;
-webkit-animation: spin 2s reverse;
-moz-animation-fill-mode: forwards;
-webkit-animation-fill-mode: forwards;
}
@keyframes spin {
from {
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}
to {
-webkit-transform: rotate(180deg);
transform: rotate(180deg);
}
}
body {
text-align: center;
margin: 0 auto;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Keyframes are not supported in IE9 and earlier</h2>
<div class="box">
<div class="top">top</div>
<div class="caret"><i class="fa fa-caret-square-o-up"></i>
</div>
<div class="bottom">bottom</div>
</div>
<p>
<button id="btnf">SPIN CLOCKWISE</button>
</p>
<p>
<button id="btnb">SPIN COUTNER CLOCKWISE</button>
</p>
【问题讨论】:
-
您使用动画有什么特别的原因吗?使用过渡而不是动画来实现这一点会容易得多。
-
谢谢哈利,我会研究过渡。
-
感谢 Harry、Chris 和 oMiKeY 的精彩回答!如果事实证明我使用了转换(这听起来是更好的方法),我仍然很高兴我尝试了这条路线来获得学习体验。在此之前我从来没有搞乱过 CSS 动画,我学到了很多东西。
标签: javascript jquery css css-animations