我想每 5 秒摇动一下这个文本,所以我尝试在 CSS 中实现一个动画并通过 jQuery 设置一个间隔,但似乎有些不对劲……想法缺少了什么?这是一个 fiddle :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>
最佳答案
您可以使用纯 CSS 来完成,不需要 JS/jQuery。为了实现这一点,我将 animation-duration
设置为 5 秒,然后将所有百分比值乘以 0.2(因为 5 秒中的 1 秒 => 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>
关于javascript - 每 5 秒/间隔运行一次动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47136168/