CSS强制动画在点击、活动或聚焦时完全完成



给定:

.button_focus, .button_active {
width: 8rem;
height: 5rem;
background-color: #e4e7eb;
}
.button_focus:focus,
.button_active:active {
animation-name: clickAnimation;
animation-duration: 250ms;
animation-timing-function: ease-in-out;
}
@KeyFrames clickAnimation {
0.00% { background-color: #d5d7da; }
14.29% { background-color: #ced0d3; }
28.57% { background-color: #bbbbbb; }
42.86% { background-color: #b1b2b3; }
57.14% { background-color: #b1b2b3; }
71.43% { background-color: #bbbbbb; }
85.71% { background-color: #ced0d3; }
100.00% { background-color: #d5d7da; } 
}
<div class="contianer">
<button class="button_focus">
focus
</button>
<button class="button_active">
active
</button>
</div>

我想找到一种方法,能够垃圾邮件点击按钮和动画完全处理的每一次。目前,对于:focus伪类,我需要单击按钮,然后单击离开,以便在再次单击按钮时重新初始化动画。

相反,如果我使用:active伪类,则在每次连续单击时都会播放动画,但它并没有完全完成。我需要按下250ms的按钮才能完全完成动画。


SO上有一些关于这件事的帖子,解决方案似乎是使用JS添加一个动画类,然后将其删除,但在大多数帖子中,问题都涉及悬停。在我的情况下,这只是一次点击,所以我不明白如何添加一个动画类,并在某个时候删除它。我想我只是感到困惑。

有人有什么想法或建议吗?

问题是焦点和活动伪类有点太过延迟或太过短暂——因此,为了摆脱fous,用户必须离开并保持活动,他们必须不断按下。

使用JS我们可以监听点击按钮,添加一个设置动画的类。

我们为按钮上的animationend事件保留一个永久监听,当它被触发时,我们删除该类。这样,动画在完成之前不会被"干扰",但我们确实需要删除它,以便在下次单击时可以再次设置它(否则,如果设置没有更改,CSS认为它已经完成了)。

const button = document.querySelector('.button_click');
button.addEventListener('click', function() {
button.classList.add('clicked');
});
button.addEventListener('animationend', function() {
button.classList.remove('clicked');
});
.button_click {
width: 8rem;
height: 5rem;
background-color: #e4e7eb;
animation-name: none;
}
.button_click.clicked {
animation-name: clickAnimation;
animation-duration: 250ms;
animation-timing-function: ease-in-out;
}
@KeyFrames clickAnimation {
0.00% {
background-color: #d5d7da;
}
14.29% {
background-color: #ced0d3;
}
28.57% {
background-color: #bbbbbb;
}
42.86% {
background-color: #b1b2b3;
}
57.14% {
background-color: #b1b2b3;
}
71.43% {
background-color: #bbbbbb;
}
85.71% {
background-color: #ced0d3;
}
100.00% {
background-color: #d5d7da;
}
}
<div class="contianer">
<button class="button_click">
click me
</button>
</div>

最新更新