Javascript 简明教程
JavaScript - DOM Animation
DOM animation 可以通过使用 JavaScript 改变 DOM 元素的样式来实现。当变化逐渐发生且时间间隔较短时,动画看起来会连续。通常,有三种方法来使一个 DOM 元素动起来:
The DOM animation can be achieved by changing the DOM element’s style using JavaScript. When changes are gradual and time interval is small, the animation looks continuous. Generally, there are three ways to animate a DOM element:
-
Using CSS transitions − It utilizes pre-defined animation styles in CSS triggered by changes in the element’s properties.
-
Using CSS animations − It offers more control over animation timing and behavior by defining keyframes and animation properties within the CSS file.
-
Using JavaScript − It provides the most flexibility, allowing you to dynamically manipulate style properties and create complex animations directly within your JavaScript code.
本章提供了如何使用 JavaScript 使 DOM 元素动起来的基础知识。
This chapter provides a basic understanding of how to animate DOM elements using JavaScript.
Animate DOM Elements with JavaScript
JavaScript 可用于改变 DOM 元素的样式。
JavaScript can be used to change the style of the DOM element.
你可以在一个特定的时间范围之后改变 DOM 元素的样式,以使它们动起来。例如,你可以使用 setInterval() 方法改变 DOM 元素的位置,让它从一个位置移动到另一个位置,并且带有动画效果。
You change the style of the DOM element after a particular time frame to animate them. For example, you can use the setInterval() method to change the position of the DOM element to move it from one position to another with animation.
类似地,你可以更新像“动画”这样的 CSS 属性,以使元素动态地动起来。
Similarly, you can update CSS properties like ‘animation’, etc., to animate the element dynamically.
此外,requestAnimationFrame() 方法也可以用来使 DOM 元素动起来。
Furthermore, the requestAnimationFrame() method can also be used to animate the DOM elements.
下面,你将学习使 DOM 元素动起来的多种方法。
Below, you will learn different ways to animate the DOM elements.
Animate DOM elements using setInterval() method
你可以在每次时间范围之后调用一个 setInterval() 方法,并改变 DOM 元素的样式来使它们动起来。但是,你可以保持较短的时间范围来让动画流畅地运行。
You can invoke a setInterval() method after each time frame and change the style of the DOM element to animate them. However, you can keep the time frame small to run animation smoothly.
Syntax
按照以下语法使用 setInterval() 方法来使 DOM 元素动起来。
Follow the syntax below to use the setInterval() method to animate DOM elements.
let id = setInterval(frame_func, timeframe);
function frame_func() {
if (animation_end) {
clearInterval(id);
} else {
// change style to animate
}
}
在上面的语法中,我们使用 setInterval() 方法启动动画,并在每隔“timeframe”毫秒之后调用 frame_func() 函数。
In the above syntax, we start the animation using the setInterval() method and call the frame_func() after every ‘timeframe’ milliseconds.
在 frame_func() 函数中,我们定义了结束或继续动画的条件。
In the frame_func() function, we have defined the condition to end or continue the animation.
Example
在下面的代码中,我们对 <div> 元素设置了样式。
In the below code, we have styled the <div> elements.
当用户点击按钮时,它会调用 startAnimation() 函数。
When users click the button, it calls the startAnimation() function.
在 startAnimation() 函数中,我们定义了“pos”变量,并用 0 对其进行了初始化,0 代表 div 元素的初始位置。
In the startAnimation() function, we have defined the ‘pos’ variable and initialized it with 0, representing the initial position of the div element.
在那之后,我们使用了 setInterval() 方法在每隔 5 毫秒之后调用 animationFrame() 函数。
After that, we used the setInterval() method to invoke the animationFrame() function after every 5 milliseconds.
在 animationFrame() 函数中,如果内部 div 的位置变为 350,我们使用 clearInterval() 方法停止动画。否则,我们更改内部 div 的左侧位置。
In the animationFrame() function, if the position of the inner div becomes 350, we stop the animation using the clearInterval() method. Otherwise, we change the left position of the inner div.
当您单击按钮时,它会将内部 div 元素从左向右移动。
When you click the button, it will move the inner div element from left to right.
<!DOCTYPE html>
<html>
<head>
<style>
#parent {
width: 700px;
height: 50px;
position: relative;
background: yellow;
}
#child {
width: 50px;
height: 50px;
position: absolute;
background-color: red;
}
</style>
</head>
<body>
<div id = "parent">
<div id = "child"> </div>
</div>
<br>
<button onclick = "startAnimation()"> Animate Div </button>
<script>
function startAnimation() {
const elem = document.getElementById("child");
// Starting position
let pos = 0;
// Changing frames for animation
let id = setInterval(animationFrame, 5);
function animationFrame() {
// Stop the animation
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.left = pos + "px";
}
}
}
</script>
</body>
</html>
Example
在以下代码中,<div> 元素的背景颜色为绿色。
In the below code, the background color of the <div> element is green.
我们使用 setInterval() 方法在每 50 毫秒后调用 animationFrame() 函数。
We use the setInterval() method to call the animationFrame() function after every 50 milliseconds.
在 animationFrame() 函数中,我们将 <div> 元素的不透明度更改为 0.1。当不透明度变得小于或等于 0 时,我们使用 clearInterval() 方法停止动画。
In the animationFrame() function, we change the opacity of the <div> element by 0.1. We stop the animation when the opacity becomes less than or equal to 0 using the clearInterval() method.
<!DOCTYPE html>
<html>
<head>
<style>
#parent {
width: 700px;
height: 200px;
background: green;
}
</style>
</head>
<body>
<div id = "parent">
</div>
<br>
<button onclick = "startAnimation()"> Animate Div </button>
<script>
function startAnimation() {
const parent = document.getElementById("parent");
let opacity = 1;
let id = setInterval(animationFrame, 50);
function animationFrame() {
if (opacity <= 0) {
// Stop animation
clearInterval(id);
parent.style.opacity = 1;
parent.style.backgroundColor = "red";
} else {
// Decrease the opacity
parent.style.opacity = opacity;
opacity = opacity - 0.1;
}
}
}
</script>
</body>
</html>
Animate DOM elements using requestAnimationFrame() method
requestAnimationFrame() 方法用于像 setInterval() 方法一样给 DOM 元素做动画。它会连续执行任务,并在浏览器中重新绘制下一帧。
The requestAnimationFrame() method is used to animate the DOM elements like the setInterval() method. It executes the tasks continuously and repaints the next frame in the browser.
requestAnimationFrame() 方法比 setInterval() 方法让渲染更加高效。
The requestAnimationFrame() method makes rendering more efficient than the setInterval() method.
Syntax
遵循以下语法,使用 requestAnimationFrame() 方法给 DOM 元素做动画。
Follow the syntax below to use the requestAnimationFrame() method to animate DOM elements.
function animate() {
// Animation logic
// Request the next animation frame
requestAnimationFrame(animate);
}
// Animation loop
animate();
让我们来理解一下 requestAnimationFrame() 方法的工作原理。
Let’s understand how the requestAnimationFrame() method works.
-
You pass the callback function as an argument of the requestAnimationFrame() method to execute the next frame.
-
The web browser will execute the callback before repainting the next frame.
-
The callback function will update the DOM element.
-
The browser will repaint the DOM element.
-
Again, the browser will call the callback function, and the loop will continue.
您可以使用 cancelAnimationFrame() 方法取消动画。
You can use the cancelAnimationFrame() method to cancel animation.
Example
在以下代码中,我们定义了 startAnimation() 和 stopAnimation() 函数,并在用户单击按钮时调用它们。
In the code below, we have defined the startAnimation() and stopAnimation() functions and invoked them when the user clicks the button.
在 startAnimation() 函数中,我们使“pos”的值增加 1,并更新子 div 元素的左侧位置。
In the startAnimation() function, we increment the value of the ‘pos’ by 1, and update the left position of the child div element.
然后,我们使用 requestAnimationFrame() 方法在 Web 浏览器中绘制下一帧。它会在父 div 元素中将子 div 元素从左向右移动。
After that, we used the requestAnimationFrame() method to paint the next frame in the web browser. It will move the child div element from left to right in the parent div element.
stopAnimation() 函数使用 cancelAnimationFrame() 方法停止动画。它将 requestAnimationFrame() 方法返回的 id 作为参数。
The stopAnimation() function uses the cancelAnimationFrame() method to stop the animation. It takes the id returned by the requestAnimationFrame() method as an argument.
<!DOCTYPE html>
<html>
<head>
<style>
#parent {width: 700px; height: 50px; position: relative;background: yellow;}
#child {width: 50px;height: 50px; position: absolute; background-color: red;}
</style>
</head>
<body>
<div id = "parent">
<div id = "child"> </div>
</div>
<br>
<button onclick = "startAnimation()"> Animate Div </button>
<button onclick = "stopAnimation()"> Stop Animation </button>
<script>
let animationId;
let pos = 0;
function startAnimation() {
const elem = document.getElementById("child");
function animationFrame() {
if (pos < 650) {
pos++;
elem.style.left = pos + "px";
// Make a call for a next frame
animationId = requestAnimationFrame(animationFrame);
}
}
// Start Animation
animationFrame();
}
function stopAnimation() {
// Stop animation
if (animationId) {
cancelAnimationFrame(animationId);
animationId = null;
}
}
</script>
</body>
</html>
Animate DOM Elements by changing the CSS Properties
CSS 的“动画”属性可以用来为 DOM 元素添加动画。JavaScript 也允许自定义“动画”属性。
The ‘animation’ property of the CSS can be used to add animation to the DOM element. JavaScript also allows the customization of the ‘animation’ property.
Syntax
请按照以下语法在 JavaScript 中,通过更改元素的“动画”属性值,为 DOM 元素添加动画。
Follow the syntax below to animate the DOM element by changing the value of the ‘animation’ property of the element in JavaScript.
element.style.animation = "key_frame_name duration timing_function iterationCount";
Property values
-
key_frame_name − It is the name of the keyframe, which you need to define in the CSS.
-
duration − It is the duration of the animation.
-
timing_function − It is used to set how animation should be executed.
-
iterationCount − It specifies how many times the animation should repeat.
Example
在下方代码中,当用户单击按钮时,我们将调用 animateDiv() 函数,并更新 div 元素的 style 对象的“动画”属性值。
In the below code, when users click the button, we call the animateDiv() function and update the value of the ‘animation’ property of the style object of the div element.
我们已经在 CSS 中定义了“moveAnimation”关键帧。所以,当您单击按钮时,它将开始移动 div 元素。
We have already defined the ‘moveAnimation’ keyframe in CSS. So, when you click the button it will start moving the div element.
<!DOCTYPE html>
<html>
<head>
<style>
#element {
width: 90px;
height: 90px;
background: blue;
color: white;
position: relative;
text-align: center;
}
@keyframes moveAnimation {
from {
transform: translateX(0);
}
to {
transform: translateX(550px);
}
}
</style>
</head>
<body>
<div id = "element"> Animate </div>
<br>
<button onclick = "animateDiv()"> Animate Div </button>
<script>
function animateDiv() {
const element = document.getElementById("element");
element.style.animation = "moveAnimation 3s ease-in-out infinite";
}
</script>
</body>
</html>
为 DOM 元素添加动画的最佳方法是使用 requestAnimationFrame() 方法,它可以平滑地为 DOM 元素添加动画。此外,它可以用于同时执行不同的动画。
The best way to animate the DOM element is using the requestAnimationFrame() method, which animates the DOM element smoothly. Also, it can be used to execute different animations simultaneously.