JavaScript 动画方式设置元素尺寸和透明度

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

使用javascript设置元素的尺寸和透明度非常的简单。

不过使用动画方式实现就更加美观和人性化一些,下面就分享一段代码实例,它实现了这样的功能。

代码如下:

<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.pipipi.net/" />
<title>犀牛前端部落</title>
<style type="text/css">
body, div{
  margin: 0;
  padding: 0;
  font-size: 12px;
}
table {
  border-collapse: collapse;
  border-spacing: 0;
}
ul {
  list-style: none;
}
.odiv {
  position: relative;
}
.odiv ul li {
  width: 200px;
  height: 100px;
  background: yellow;
  margin-bottom: 20px;
  border: 2px solid #000;
}
#li1 {
  opacity: 0.3;
  filter: alpha(opacity:30);
}
</style>
<script language="javascript">
window.onload = function () {
  var li1 = document.getElementById('li1');
  li1.onmouseover = function () {
    startMov(li1, 400, 'width', function () {
      startMov(li1, 200, 'height', function () {
        startMov(li1, 100, 'opacity');
      });
    });
  };
  li1.onmouseout = function () {
    startMov(li1, 30, 'opacity', function () {
      startMov(li1, 100, 'height', function () {
        startMov(li1, 100, 'width');
      });
    });
  };
  li1.timer = null;
  function startMov(obj, itarget, attr, fn) {
    clearInterval(obj.timer);
    obj.timer = setInterval(function () {
      var icur = 0;
      if (attr == 'opacity') {
        icur = Math.round(parseFloat(getStyle(obj, attr)) * 100);
      }
      else {
        icur = parseInt(getStyle(obj, attr));
      }
      var speed = 0;
      speed = (itarget - icur) / 8;
      speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
      if (icur == itarget) {
        clearInterval(obj.timer);
        if (fn) {
          fn();
        }
      }
      else {
        if (attr == 'opacity') {
          obj.style.filter = 'alpha(opacity:' + (icur + speed) + ')';
          obj.style.opacity = (icur + speed) / 100;
        }
        else {
          obj.style = icur + speed + 'px';
        }
      }
    }, 30);
  }
  function getStyle(obj, attr) {
    if (obj.currentStyle) {
      return obj.currentStyle;
    }
    else {
      return getComputedStyle(obj, false);
    }
  }
}
</script>
</head>
<body>
<div id="odiv" class="odiv">
  <ul>
    <li id="li1"></li>
  </ul>
</div>
</body>
</html>

回复

我来回复
  • 暂无回复内容