JavaScript元素動畫效果

antzone發表於2017-04-17

分享一段程式碼例項,它實現了js以動畫方式操作dom元素,實現改變元素屬性的功能。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style type="text/css">
* {
  margin: 0;
  padding: 0;
}
#box {
  position: absolute;
  width: 200px;
  height: 200px;
  background: red;
}
</style>
<script type="text/javascript">
window.onload = function() {
  var btn = document.getElementById("btn");
  var box = document.getElementById("box");
 
  function getStyle(obj, style) {
    if (window.getComputedStyle) {
      return window.getComputedStyle(obj, null)[style];
    } else {
      return obj.currentStyle[style];
    }
  }
 
  function animationRetard(obj, json, fn) {
    clearInterval(obj.anime);
 
    obj.anime = setInterval(function() {
      var flag = true;
 
      for (var key in json) {
        var now = parseInt(getStyle(obj, key));
 
        var step = json[key] > now ? Math.ceil((json[key] - now) / 10) : Math.floor((json[key] - now) / 10);
        now += step;
 
        if (Math.abs(json[key] - now) > Math.abs(step)) {
          obj.style[key] = now + "px";
 
          flag = false;
        } else {
          obj.style[key] = json[key] + "px";
        }
      }
 
      if (flag) {
        clearInterval(obj.anime);
        if (fn) {
          fn();
        }
      }
    }, 20);
  }
 
  btn.onclick = function() {
    animationRetard(box, {
      "width": 600,
      "height": 400,
      "top": 100,
      "left": 100
    }, function() {
      animationRetard(box, {
        "width": 300,
        "height": 200,
        "top": 50,
        "left": 50
      }, function() {
        animationRetard(box, {
          "width": 600,
          "height": 500,
          "top": 400,
          "left": 1000
        })
      })
    })
  }
}
</script>
</head>
<body>
<input id="btn" type="button" value="改變"/>
<div id="box"></div>
</body>
</html>

相關文章