Trigger CSS Animations in JavaScript

后端 未结 8 1141
粉色の甜心
粉色の甜心 2020-11-28 14:14

I don\'t know how to use JQuery, so I need a method which could trigger an animation using JavaScript only.

I need to call/trigger CSS Animation when the user scrol

相关标签:
8条回答
  • 2020-11-28 14:58

    This is how you can use vanilla JavaScript to change/trigger an animation associated with an HTML element.

    First, you define your animations in CSS.

    @keyframes spin1 { 100% { transform:rotate(360deg); } }
    @keyframes spin2 { 100% { transform:rotate(-360deg); } }
    @keyframes idle { 100% {} }
    

    Then you use javascript to switch between animations.

    document.getElementByID('yourElement').style.animation="spin2 4s linear infinite";
    

    Note: 'yourElement' is the target HTML element that you wish to animate.

    For example: <div id="yourElement"> ... </div>

    0 讨论(0)
  • 2020-11-28 14:58

    Adding and removing the animation class does not work in a function. The delay is simply to little. As suggested by this article you can request the browser to reflow and then add the class. The delay isn't an issue in that case. Hence, you can use this code:

    element.classList.remove("animation")
    element.ofsettWidth
    element.classList.add("animation")
    

    The best thing is, this works everywhere. All credit goes to the article.

    0 讨论(0)
提交回复
热议问题