How to prevent css keyframe animation to run on page load?

后端 未结 7 1872
轻奢々
轻奢々 2020-12-07 20:20

I have a div in which I animate the content:

7条回答
  •  一整个雨季
    2020-12-07 20:57

    If you're looking at this after 2019, a better solution is this:

    let div = document.querySelector('div')
    document.addEventListener('DOMContentLoaded', () => {
        // Adding timeout to simulate the loading of the page
        setTimeout(() => {
            div.classList.remove('prevent-animation')
        }, 2000)
        
        document.querySelector('button').addEventListener('click', () => {
            if(div.classList.contains('after')) {
                div.classList.remove('after')
            } else {
                div.classList.add('after')
            }
        })
    })
    div {
        background-color: purple;
        height: 150px;
        width: 150px;
    }
    
    .animated-class {
        animation: animationName 2000ms;
    }
    
    .animated-class.prevent-animation {
        animation-duration: 0ms;
    }
    
    .animated-class.after {
        animation: animation2 2000ms;
        background-color: orange;
    }
    
    @keyframes animationName {
        0% {
            background-color: red;
        }
        50% {
            background-color: blue;
        }
        100% {
            background-color: purple;
        }
    }
    
    @keyframes animation2 {
        0% {
            background-color: salmon;
        }
        50% {
            background-color: green;
        }
        100% {
          background-color: orange;
        }
    }

提交回复
热议问题