JavaScript DOM 动画


目录

    显示目录


学习使用 JavaScript 创建 HTML 动画。


一个基本的网页

为了演示如何使用 JavaScript 创建 HTML 动画,我们将使用一个简单的 网页:

例子

<!DOCTYPE html>
<html>
<body>
<h1>My First 
 JavaScript Animation</h1>

<div id="animation">My animation will go here</div>

</body>
</html>

创建动画容器

所有动画都应该与容器元素相关。

例子

<div id ="container">
  <div id ="animate">My 
 animation will go here</div>
</div>

元素样式

容器元素应使用 style="position:relative" 创建。

动画元素应使用 style="position:absolute" 创建。

例子

#container {
  width: 400px;
  height: 
 400px;
  position: relative;
  
 background: yellow;
 }
#animate {
  width: 50px;
  height: 
 50px;
  position: absolute;
  
 background: red;
}

自己尝试一下 →

<!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 动画是通过对元素的渐变进行编程来完成的 风格。

这些更改由计时器调用。当定时器间隔较小时, 动画看起来是连续的。

基本代码是:

例子

id = setInterval(frame, 5);
function frame() {
  if (/* 
 test for finished */) {
    clearInterval(id);
  } else {
      
 /* code to change the element style */  
  }
}

使用 JavaScript 创建完整的动画

例子

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'; 
      }
  }
}

自己尝试一下 →

<!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>