我正在制作一个应用程序,其中有一个复选框用于控制是否在屏幕上显示覆盖。为了使外观和消失更平滑,我添加了动画。
#overlay{
position:absolute;
height: 100vh;
width: 100vw;
background-color: white;
display:none;
animation-name: none;
animation-play-state: paused;
animation-fill-mode: forwards;
animation-duration: 1s;
opacity: 0;
}
@keyframes appear {
0%{opacity: 0}
100%{opacity: 1}
}
@keyframes disappear {
0%{opacity: 1}
100%{opacity: 0}
}
然后在这里我使用js调用这些动画。
function handleChange(checkbox) {
const animation = document.getElementById("overlay");
if(checkbox.checked === true){
if (window.innerWidth < 846) {
animation.style.display="block";
animation.style.animationName="appear";
animation.style.animationPlayState = "running";
document.getElementById('overlay2').style.display="none";
disableScroll();
}
return false;
}else{
animation.style.animationName="disappear";
animation.style.animationPlayState="running";
animation.addEventListener('animationend', () => {
animation.style.display="none";
document.getElementById("overlay2").style.display="block";
})
enableScroll();
return false;
}
}
动画在首次选中和未选中时均能完美运行。但是,如果我重复此操作并第二次选中该框,它就会崩溃。 也许有帮助吗?谢谢!
答案 0 :(得分:2)
因为您每次都添加了事件监听器。
解决方案:
function handleChange(checkbox) {
const animation = document.getElementById("overlay");
if(checkbox.checked === true){
if (window.innerWidth < 846) {
animation.style.display="block";
animation.style.animationName="appear";
animation.style.animationPlayState = "running";
document.getElementById('overlay2').style.display="none";
disableScroll();
}
return false;
} else {
animation.style.animationName="disappear";
animation.style.animationPlayState="running";
const singleEvent = () => {
animation.style.display="none";
document.getElementById("overlay2").style.display="block";
animation.removeEventListener('animationend', singleEvent)
};
animation.addEventListener('animationend', singleEvent);
enableScroll();
return false;
}
}