JavaScript動畫方式改變元素寬度和高度

admin發表於2017-04-16

分享一段程式碼例項,它實現了以動畫方式改變元素寬度和高度效果。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style type="text/css">
div {
  width: 100px;
  height: 100px;
  background-color: #F70;
  border: 5px solid #689;
  margin: 5px;
  float: left;
}
 
div p {
  font-size: 32px;
  color: #fff;
  text-align: center;
}
</style>
<script>
window.onload = function() {
  var div_1 = document.getElementById("div1");
  var div_2 = document.getElementById("div2");
 
  this.timer = null;
 
  div_1.onmouseover = function() {
    startMove(this, "height", 400);
  }
  div_1.onmouseout = function() {
    startMove(this, "height", 100);
  }
 
  div_2.onmouseover = function() {
    startMove(this, "width", 400);
  }
 
  div_2.onmouseout = function() {
    startMove(this, "width", 100);
  }
}
 
//獲取行間樣式函式
function getStyle(obj, name) {
  if (obj.currentStyle) {
    return obj.currentStyle[name];
  } else {
    return getComputedStyle(obj, false)[name];
  }
}
 
function startMove(obj, name, iTarget) {
  clearInterval(obj.timer);
  obj.timer = setInterval(function() {
    var sty = parseInt(getStyle(obj, name));
    var speed = (iTarget - sty) / 20;
    speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
    if (sty == iTarget) {
      clearInterval(obj.timer);
    } else {
      obj.style[name] = sty + speed + "px";
    }
  }, 30);
}
</script>
</head>
<body>
  <div id="div1"><p></p></div>
  <div id="div2"><p></p></div>
</body>
</html>

相關文章