Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
125 views
in Technique[技术] by (71.8m points)

html - Trigger CSS Animations in JavaScript

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 scrolls the page.

function start() {
  document.getElementById('logo').style.animation = "anim 2s 2s forward";
  document.getElementById('earthlogo').style.animation = "anim2 2s 2s forward";
}
* {
  margin: 0px;
}

#logo {
  position: fixed;
  top: 200px;
  height: 200px;
  width: 1000px;
  left: 5%;
  z-index: 4;
  opacity: 0.8;
}

#earthlogo {
  position: fixed;
  top: 200px;
  height: 120px;
  align-self: center;
  left: 5%;
  margin-left: 870px;
  margin-top: 60px;
  z-index: 4;
  opacity: 0.9;
}

@keyframes anim {
  50% {
    filter: blur(10px);
    transform: rotate(-15deg);
    box-shadow: 0px 0px 10px 3px;
  }
  100% {
    height: 100px;
    width: 500px;
    left: 10px;
    top: 10px;
    box-shadow: 0px 0px 15px 5px rgba(0, 0, 0, 0.7);
    background-color: rgba(0, 0, 1, 0.3);
    opacity: 0.7;
  }
}

@keyframes anim2 {
  50% {
    filter: blur(40px);
    transform: rotate(-15deg);
  }
  100% {
    height: 60px;
    width: 60px;
    left: 10px;
    top: 10px;
    margin-left: 435px;
    margin-top: 30px;
    opacity: 0.8;
  }
}

#backstar {
  position: fixed;
  width: 100%;
  z-index: 1;
}

#earth {
  position: absolute;
  width: 100%;
  z-index: 2;
  top: 300px;
}
<img src="logo.png" id="logo" onclick="start();">
<img src="earthlogo.gif" id="earthlogo" onscroll="start();">
<img src="earth.png" id="earth">
<img src="stars.jpg" id="backstar">
question from:https://stackoverflow.com/questions/44846614/trigger-css-animations-in-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

There is a similar question here: Trigger a CSS keyframe animation via scroll


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...