Erfahren Sie, wie Sie HTML-Animationen mit JavaScript erstellen.
Um zu demonstrieren, wie man HTML-Animationen mit JavaScript erstellt, verwenden wir eine einfache Website:
<!DOCTYPE html>
<html>
<body>
<h1>My First
JavaScript Animation</h1>
<div id="animation">My animation will go here</div>
</body>
</html>
Alle Animationen sollten relativ zu einem Containerelement sein.
<div id ="container">
<div id ="animate">My
animation will go here</div>
</div>
Das Containerelement sollte mit style=„position: relative
“ erstellt werden.
Das Animationselement sollte mit style=„position: absolute
“ erstellt werden.
#container {
width: 400px;
height:
400px;
position: relative;
background: yellow;
}
#animate {
width: 50px;
height:
50px;
position: absolute;
background: red;
}
Probieren Sie es selbst aus →
<!Doctype html>
<html>
<style>
#container {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#animate {
width: 50px;
height: 50px;
position: absolute;
background: red;
}
</style>
<body>
<h2>My First JavaScript Animation</h2>
<div id="container">
<div id="animate"></div>
</div>
</body>
</html>
JavaScript-Animationen werden durch die Programmierung schrittweiser Änderungen an einem Element erstellt Stil.
Die Änderungen werden von einem Timer aufgerufen. Wenn das Timer-Intervall klein ist, wird die Die Animation sieht kontinuierlich aus.
Der Grundcode lautet:
id = setInterval(frame, 5);
function frame() {
if (/*
test for finished */) {
clearInterval(id);
} else {
/* code to change the element style */
}
}
function myMove() {
let id = null;
const elem = document.getElementById("animate");
let pos = 0;
clearInterval(id);
id = setInterval(frame, 5);
function frame() {
if (pos ==
350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
}
}
}
Probieren Sie es selbst aus →
<!DOCTYPE html>
<html>
<style>
#container {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#animate {
width: 50px;
height: 50px;
position: absolute;
background-color: red;
}
</style>
<body>
<p><button onclick="myMove()">Click Me</button></p>
<div id ="container">
<div id ="animate"></div>
</div>
<script>
function myMove() {
let id = null;
const elem = document.getElementById("animate");
let pos = 0;
clearInterval(id);
id = setInterval(frame, 5);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + "px";
elem.style.left = pos + "px";
}
}
}
</script>
</body>
</html>