JavaScript 動畫方式設定元素尺寸和透明度

antzone發表於2017-04-12

使用javascript設定元素的尺寸和透明度非常的簡單。

不過使用動畫方式實現就更加美觀和人性化一些,下面就分享一段程式碼例項,它實現了這樣的功能。

程式碼如下:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<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[attr] = icur + speed + 'px';
        }
      }
    }, 30);
  }
  function getStyle(obj, attr) {
    if (obj.currentStyle) {
      return obj.currentStyle[attr];
    }
    else {
      return getComputedStyle(obj, false)[attr];
    }
  }
}
</script>
</head>
<body>
<div id="odiv" class="odiv">
  <ul>
    <li id="li1"></li>
  </ul>
</div>
</body>
</html>

相關文章