JavaScript HTML DOM 动画

155 阅读1分钟

学习使用 JavaScript 来创建 HTML 动画。

创建动画容器

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

<div id ="container">
    <div id ="animate">我的动画在这里。</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;
} 

然后

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

效果

w3xrw-qzsy3.gif

也可以组合动画,比如边移动便改变他的大小。

function myMove() {
  var elem =  document.getElementById("animate");
  var pos = 0;
  var width = 50;
  var id = setInterval(frame, 2);
  function frame() {
    if (pos ==  300) {
      clearInterval(id);
    } else {
      pos++;
      elem.style.top = pos + 'px';
      elem.style.left = pos + 'px';
    }
  }
  var id2 = setInterval(changeSize, 25);
  function  changeSize(){
    if (width == 100){
        clearInterval(id2)
    }else{
      width++
      elem.style.width = width  + 'px';
      elem.style.height = width  + 'px';
    }
  }
}

效果如下:

63ktp-he6t4.gif