我想每隔5秒摇一次这个文字,所以我尝试在CSS中实现一个动画,并通过jQuery设置一个间隔,但似乎有些不对劲......想法缺少什么?这是一个小提琴:https://jsfiddle.net/s909gu2s/1/
.shk {
transform: translate3d(0, 0, 0);
backface-visibility: hidden;
-webkit-animation-name: shake;
-webkit-animation-duration: 1s;
-webkit-animation-iteration-count: infinite;
-webkit-animation-timing-function: linear;
-webkit-animation-delay: 0s;
}
@keyframes shakeMe {
10%, 90% {
transform: translate3d(-5px, 0, 0);
}
20%, 80% {
transform: translate3d(5px, 0, 0);
}
30%, 50%, 70% {
transform: translate3d(-5px, 0, 0);
}
40%, 60% {
transform: translate3d(5px, 0, 0);
}
}
$(document).ready(function() {
setInterval(function() {
$(".shk").css("animation", "shakeMe");
}, 500);
});
<div class="shk">Shake me</div>
答案 0 :(得分:4)
你可以用纯CSS做,不需要JS / jQuery。为了实现这一点,我将animation-duration
设置为5秒,然后将所有百分比值乘以0.2(因为5秒内的1秒=&gt; 20%)。然后在最高百分比值之后转换回0px。瞧,每5秒钟摇晃一次:
.shk {
transform: translate3d(0, 0, 0);
backface-visibility: hidden;
animation-name: shakeMe;
animation-duration: 5s;
animation-iteration-count: infinite;
animation-timing-function: linear;
}
@keyframes shakeMe {
2%, 18% {
transform: translate3d(-5px, 0, 0);
}
4%, 16% {
transform: translate3d(5px, 0, 0);
}
6%, 10%, 14% {
transform: translate3d(-5px, 0, 0);
}
8%, 12% {
transform: translate3d(5px, 0, 0);
}
18.1% {
transform: translate3d(0px, 0, 0);
}
}
<div class="shk">Shake me</div>
答案 1 :(得分:3)
<强> Working fiddle 强>
首先,您应该在CSS规则中调整动画shake
的名称,以匹配名称的正确名称shakeMe
:
.shk {
transform: translate3d(0, 0, 0);
backface-visibility: hidden;
-webkit-animation-name: shake;
-webkit-animation-duration: 1s;
-webkit-animation-iteration-count: infinite;
-webkit-animation-timing-function: linear;
-webkit-animation-delay: 0s;
}
然后,您可以在时间间隔内切换类,以便每隔X毫秒恢复一次测试:
$(document).ready(function() {
setInterval(function() {
$("#target").toggleClass('shk');
}, 500);
});
希望这有帮助。
$(document).ready(function() {
setInterval(function() {
$("#target").toggleClass('shk');
}, 5000);
});
&#13;
.shk {
transform: translate3d(0, 0, 0);
backface-visibility: hidden;
-webkit-animation-name: shakeMe;
-webkit-animation-duration: 1s;
-webkit-animation-iteration-count: infinite;
-webkit-animation-timing-function: linear;
-webkit-animation-delay: 0s;
}
@keyframes shakeMe {
10%,
90% {
transform: translate3d(-5px, 0, 0);
}
20%,
80% {
transform: translate3d(5px, 0, 0);
}
30%,
50%,
70% {
transform: translate3d(-5px, 0, 0);
}
40%,
60% {
transform: translate3d(5px, 0, 0);
}
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="target" class="shk">Shake me</div>
&#13;