[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/ru/docs/Web/API/Web_Animations_API/Tips [Back]  [Original]

CSS Animations tips and tricks - API | MDN

This page was translated from English by the community. Learn more and join the MDN Web Docs community.

View in English Always switch to English

CSS Animations tips and tricks

CSS- , . , , , , . , , . , .

In this article

CSS Animations . resetAnimation () , animation-play-state " running " . , .

, .

HTML

-, HTML <div> , , ( ) .

html
<div class="box"></div>

<div class="runButton">Click me to run the animation</div>

CSS

CSS. CSS, ( ""), , .

css
@keyframes colorchange {
  0% {
    background: yellow;
  }
  100% {
    background: blue;
  }
}

.box {
  width: 100px;
  height: 100px;
  border: 1px solid black;
}

.changing {
  animation: colorchange 2s;
}

. "box" , - . "changing" , , @keyframes "colorchange" 2 .

, - , .. .

JavaScript

JavaScript, . play (), , "".

js
function play() {
  document.querySelector(".box").className = "box";
  window.requestAnimationFrame(function (time) {
    window.requestAnimationFrame(function (time) {
      document.querySelector(".box").className = "box changing";
    });
  });
}

, ? , - , , , , . , .

, play() :

  1. CSS "box". , , "changing" , . , . , , .
  2. , , window.requestAnimationFrame() . . ,, , !
  3. requestAnimationFrame() ! , , . "changing" , .

, "", - :

js
document.querySelector(".runButton").addEventListener("click", play, false);

animation-name , . , , , . :

  1. , . , animation-direction: alternate. , .
  2. JavaScript , animationiteration.

, JavaScript:

css
.slidein {
  animation-duration: 5s;
  animation-name: slidein;
  animation-iteration-count: infinite;
}

.stopped {
  animation-name: none;
}

@keyframes slidein {
  0% {
    margin-left: 0%;
  }
  50% {
    margin-left: 50%;
  }
  100% {
    margin-left: 0%;
  }
}
html
<h1 id="watchme">Click me to stop</h1>
js
let watchme = document.getElementById("watchme");

watchme.className = "slidein";
const listener = (e) => {
  watchme.className = "slidein stopped";
};
watchme.addEventListener("click", () =>
  watchme.addEventListener("animationiteration", listener, false),
);

Demo https://jsfiddle.net/morenoh149/5ty5a4oy/


Web Proxy Viewer  |  New URL  |  Original Page