JS动画碾压

我正在制作一个应用程序,其中复选框控制覆盖是否出现在屏幕上。为了使出现和消失平滑,我添加了动画。


#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;

    }

}

首次选中和取消选中时,动画效果完美。但是,如果我重复此操作并第二次选中该框,它就会被压碎。也许有一点帮助?谢谢你!


动漫人物
浏览 124回答 1
1回答

DIEA

因为您每次都添加了事件侦听器。解决方案:function handleChange(checkbox) {&nbsp; &nbsp; const animation = document.getElementById("overlay");&nbsp; &nbsp; if(checkbox.checked === true){&nbsp; &nbsp; &nbsp; &nbsp; if (window.innerWidth < 846) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; animation.style.display="block";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; animation.style.animationName="appear";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; animation.style.animationPlayState = "running";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.getElementById('overlay2').style.display="none";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; disableScroll();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; animation.style.animationName="disappear";&nbsp; &nbsp; &nbsp; &nbsp; animation.style.animationPlayState="running";&nbsp; &nbsp; &nbsp; &nbsp; const singleEvent = () => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; animation.style.display="none";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.getElementById("overlay2").style.display="block";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; animation.removeEventListener('animationend', singleEvent)&nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; &nbsp; &nbsp; animation.addEventListener('animationend', singleEvent);&nbsp; &nbsp; &nbsp; &nbsp; enableScroll();&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript