JavaScript动画方式改变元素宽度和高度

快乐打工仔 分类:实例代码

分享一段代码实例,它实现了以动画方式改变元素宽度和高度效果。

代码实例如下:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.pipipi.net/" />
<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>

JavaScript动画方式改变元素宽度和高度,这样的场景在实际项目中还是用的比较多的,关于JavaScript动画方式改变元素宽度和高度就介绍到这了。

JavaScript动画方式改变元素宽度和高度属于前端实例代码,有关更多实例代码大家可以查看

回复

我来回复
  • 暂无回复内容