js移入和離開動畫方式改變透明度

admin發表於2017-04-17

分享一段程式碼例項,它實現了滑鼠懸浮透明度動畫漸變效果。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style type="text/css">
#div1 {
  width: 100px;
  height: 100px;
  background-color: red;
}
</style>
</head>
<body>
  <div id="div1">
  </div>
</body>
<script>
var oDiv1 = document.getElementById("div1");
oDiv1.onmouseover = function() {
  linerMove(this, "opacity", 30, -1);
}
oDiv1.onmouseout = function() {
  linerMove(this, "opacity", 100, 1)
}
 
function linerMove(obj, attr, iTarget, speed) {
  clearInterval(obj.timer);
  obj.timer = setInterval(function() {
    var attrValue = getStyle(obj, attr);
    if (attr == "opacity") {
      attrValue = attrValue * 100
    } else {
      attrValue = parseInt(attrValue);
    }
    if (Math.abs(iTarget - attrValue) <= Math.abs(speed)) {
      if (attr == "opacity") {
        obj.style[attr] = iTarget / 100;
      } else {
        obj.style[attr] = iTarget + "px";
      }
      clearInterval(obj.timer);
    } else {
      if (attr == "opacity") {
        obj.style[attr] = (attrValue + speed) / 100;
      } else {
        obj.style[attr] = attrValue + speed + "px";
      }
    }
  }, 30);
}
 
function getStyle(obj, attr) {
  if (obj.currentStyle) {
    return obj.currentStyle[attr]; //針對IE
  } else {
    return getComputedStyle(obj)[attr]; //相對其他瀏覽器
  }
}
 
function linerMove(obj, attr, iTarget, speed) {
  clearInterval(obj.timer);
  obj.timer = setInterval(function() {
    var attrValue = getStyle(obj, attr);
    attrValue = attrValue * 100; //Math.abs()絕對值
    if (Math.abs(iTarget - attrValue) <= Math.abs(speed)) {
      obj.style[attr] = iTarget / 100;
      clearInterval(obj.timer);
    } else {
      obj.style[attr] = (attrValue + speed) / 100;
    }
  }, 20);
}
 
function getStyle(obj, attr) {
  if (obj.currentStyle) {
    return obj.currentStyle[attr]; //針對IE
  } else {
    return getComputedStyle(obj)[attr]; //相對其他瀏覽器
  }
}
</script>
</html>

使用js程式碼一個好處可以相容低版本的IE瀏覽器,但是實在是太麻煩了。

使用css3比較方便,具體可以參閱css實現透明度漸變效果一章節。

相關文章