Trigger CSS Animations in JavaScript

巧了我就是萌 提交于 2019-11-27 09:14:54

The simplest method to trigger CSS animations is by adding or removing a class - how to do this with pure Javascript you can read here:

How do I add a class to a given element?

If you DO use jQuery (which should really be easy to learn in basic usage) you do it simply with addClass / removeClass.

All you have to do then is set a transition to a given element like this:

.el {
width:10px;
transition: all 2s;
}

And then change its state if the element has a class:

.el.addedclass {
width:20px;
}

Note: This example was with transition. But for animations its the same: Just add the animation on the element which has a class on it.

Similar question here: Trigger a CSS keyframe animation via scroll

You could use CSS to hide the image / animation and show when the user scrolls. This would work like this:

CSS:

div {
    border: 1px solid black;
    width: 200px;
    height: 100px;
    overflow: scroll;
}

#demo{
    display: none;
}

HTML:

<div id="myDIV"> </div>

<div id="demo">
     <img src="earthlogo.gif" id="earthlogo" alt="Thanks for scrolling. Now you see me">
</div>

Your javascript just needs to include an eventListener to call the function which triggers the display of your animation.

JS:

document.getElementById("myDIV").addEventListener("scroll", start);

function start() {
    document.getElementById('demo').style.display='block';
}

Vanilla JS version

document.getElementById('logo').classList.add("anim");
document.getElementById('earthlogo').classList.add("anim2");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!