JavaScript HTML DOM animation
- Try it yourself Previous page
- Next page DOM events
Lär dig att skapa HTML-animation med JavaScript.
Grundläggande sida
För att visa hur man skapar HTML-animation med JavaScript, kommer vi att använda en enkel webbsida:
Use JavaScript to create animation
<!DOCTYPE html> <html> <body> <h1>Min första JavaScript-animation</h1> <div id="animation">Min animation finns här.</div> </body> </html>
Skapa animationcontainer
Alla animationer bör vara kopplade till container-elementet.
Use JavaScript to create animation
<div id ="container"> <div id ="animate">Min animation finns här.</div> </div>
lägg till stil till element
bör skapas genom att använda style = "position: relative
" skapa container-element.
bör skapas genom att använda style = "position: absolute
" skapa animationselement.
Use JavaScript to create animation
#container { width: 400px; height: 400px; position: relative; background: yellow; elem.style.left = pos + 'px'; #animate { width: 50px; height: 50px; height: 50px; position: absolute; elem.style.left = pos + 'px';
background: red;
Animation code
JavaScript animation is programmed by gradually changing the element style.
This change is made through a counter call. When the counter interval is very small, the animation looks continuous.
Use JavaScript to create animation
var pos = 0; var id = setInterval(frame, 5); Basic code is: if (pos == 350) { clearInterval(id); if (/* Test if completed */) { elem.style.left = pos + 'px'; elem.style.left = pos + 'px';
/* Change element style code */
Use JavaScript to create animation
Example function myMove() { var elem = document.getElementById("animate"); var pos = 0; var id = setInterval(frame, 5); function frame() { if (pos == 350) { clearInterval(id); } else { pos++; elem.style.top = pos + 'px'; elem.style.left = pos + 'px'; elem.style.left = pos + 'px'; elem.style.left = pos + 'px';
- Try it yourself Previous page
- Next page DOM events