要在计时器上发生的 CSS 动画,用于创建检测信号动画



下面的代码片段显示了一个旋转的圆圈。每 1 秒我希望这个圆圈的大小翻倍,然后缩小到原来的大小(看起来像心跳(。我尝试这样做的方法是在javascript中创建一个计时器,以便每隔一秒,导致增长效果的类从圆圈中删除,然后立即重新添加。我希望在删除后重新添加该类会触发动画,但我想不会。现在,"心跳"只发生一次。

如果可能的话,我也想让圆圈以恒定的速度旋转。现在这个圈子在最后真的变慢了,开始有点慢。

// set timeout
let tid = setTimeout(mycode, 1000);
function mycode() {
// do some stuff...
let ic = document.getElementById('inner-circle')
ic.classList.remove('heartbeat')
ic.classList.add('heartbeat')
tid = setTimeout(mycode, 1000); // repeat myself
}
function abortTimer() { // to be called when you want to stop the timer
clearTimeout(tid);
}
#spinning-circle {
animation-name: spinning-circle;
animation-duration: 10s;
animation-iteration-count: infinite;
width: 40px;
height: 40px;
}
.heartbeat {
width: 100%;
height: 100%;
animation-name: heartbeat;
animation-duration: 0.15s;
animation-iteration-count: 2;
animation-direction: alternate;
animation-fill-mode: both;
}
#inner-circle img {
width: 100%;
height: auto;
}
@-webkit-keyframes heartbeat {
100% {
transform: scale(2,2);
-webkit-transform: scale(2,2);
}
}
@-webkit-keyframes spinning-circle {
0% {
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}
100% {
-webkit-transform: rotate(360deg);
transform: rotate(360deg);
}
}
<div id="spinning-circle">
<div id='inner-circle'>
<img src="https://i.stack.imgur.com/WbNlQ.jpg">
</div>
</div>

使用setInterval()clearInterval()而不是setTimeout(),并删除函数setTimeout()mycode()

// set timeout
let tid = setInterval(mycode, 1000);
function mycode() {
// do some stuff...
let ic = document.getElementById('inner-circle')
ic.classList.remove('heartbeat')
ic.classList.add('heartbeat')
}
function abortTimer() { // to be called when you want to stop the timer
clearInterval(tid);
}

对于动画速度,将animation-timing-function: linear;添加到.heartbeat {} and #spinning-circle {}

你根本不需要javascript:

#spinning-circle {
margin-top: 40px;
margin-left: 40px;
animation: spinning-circle linear 10s infinite;
width: 40px;
height: 40px;
overflow: visible;
}
#inner-circle {
animation: heartbeat 1s infinite;
}
#inner-circle img {
width: 100%;
height: auto;
}
@keyframes heartbeat {
0% {
transform: scale(1);
}
25% {
transform: scale(2);
}

50% {
transform: scale(1);
}

100% {
transform: scale(1);
}
}
@keyframes spinning-circle {
0% {
transform: rotate(0turn);
}
100% {
transform: rotate(-1turn);
}
}
<div id="spinning-circle">
<div id='inner-circle'>
<img src="https://i.stack.imgur.com/WbNlQ.jpg">
</div>
</div>

最新更新