我已经尝试使用 transitionend
和 animationend
在 transition
或 keyframes
动画结束后更改我的 css .我用这两种变体做了一个例子,它们按预期工作:当 transition
或动画结束时,我可以切换
class
。悬停时,我启动过渡/动画,并在 JavaScript
中切换一个类,它会在过渡/动画更改后更改 background-color
。
唯一的区别是,当我执行 mouseout 并且 div 返回到原始状态时,使用 transition
和 transitionend,类将被删除并且原始的 background-color
是可见的。对于 keyframes
动画和 animationend
,类和 background-color
保留,当我执行 mouseout 时也是如此。如何为 animationend
获得与 transition
相同的行为?
var boxTransition = document.getElementById("transition");
var boxAnimation = document.getElementById("animation");
/* add class after transition ends */
boxTransition.addEventListener("transitionend", changeBackground);
/* add class after keyframes animation ends */
boxAnimation.addEventListener("animationend", changeBackground);
function changeBackground() {
this.classList.toggle("box--end");
}
.box {
height: 100px;
margin-bottom: 30px;
width: 100px;
}
.box--transition {
background-color: lightcoral;
transition: width 0.5s ease-in-out;
}
.box--transition:hover {
width: 300px;
}
.box--animation {
background-color: lightblue;
}
.box--animation:hover {
animation: animateWidth 0.5s ease-in-out;
animation-fill-mode: forwards;
}
.box--end {
background-color: gray;
}
@keyframes animateWidth {
from {
width: 100px;
}
to {
width: 300px;
}
}
<div id="transition" class="box box--transition"></div>
<div id="animation" class="box box--animation"></div>
最佳答案
你应该注意到动画和过渡是不一样的,因此这里的事件处理有点棘手。
我将解释他们两人身上发生的事情。
过渡:它只是元素变化属性的动画部分。
例如,它可以是宽度或高度或颜色。它通常在 :hover
上分配。
因此,如果用户在转换完成之前将鼠标移出元素,它不会等待动画。
另一方面,
Animation:是一套完整的transition,不关心用户的mouseout
事件,一旦开始,它自己结束。
所以,这是您可以做的。当您在 transitionend
上分配切换时,没关系,因为只要用户将鼠标移开,转换就会完成,然后事件触发,但对于动画,您应该明确地处理它们。
我所做的是,(假设用户将鼠标在元素上停留几秒钟)在动画结束后添加类(如 transitionend
),然后在用户使用鼠标移出元素。
这不完全是你应该做的,但你现在可以知道做什么和什么时候做。
演示:
var boxTransition = document.getElementById("transition");
var boxAnimation = document.getElementById("animation");
/* add class after transition ends */
boxTransition.addEventListener("transitionend", changeBackground);
/* add class after keyframes animation ends */
boxAnimation.addEventListener("animationend", greyOnStart);
boxAnimation.addEventListener("mouseout", revertOnEnd);
function changeBackground() {
this.classList.toggle("box--end");
}
function greyOnStart(){
this.classList.add('box--end');
}
function revertOnEnd(){
this.classList.remove('box--end');
}
.box {
height: 100px;
margin-bottom: 30px;
width: 100px;
}
.box--transition {
background-color: lightcoral;
transition: width 0.5s ease-in-out;
}
.box--transition:hover {
width: 300px;
}
.box--animation {
background-color: lightblue;
}
.box--animation:hover {
animation: animateWidth 0.5s ease-in-out;
animation-fill-mode: forwards;
}
.box--end {
background-color: gray;
}
@keyframes animateWidth {
from {
width: 100px;
}
to {
width: 300px;
}
}
<div id="transition" class="box box--transition"></div>
<div id="animation" class="box box--animation"></div>
关于javascript - 删除在鼠标移出时添加了悬停和动画结束的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52961801/