js移入和离开动画方式改变透明度

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

分享一段代码实例,它实现了鼠标悬浮透明度动画渐变效果。

代码实例如下:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.pipipi.net/" />
<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 = iTarget / 100;
      } else {
        obj.style = iTarget + "px";
      }
      clearInterval(obj.timer);
    } else {
      if (attr == "opacity") {
        obj.style = (attrValue + speed) / 100;
      } else {
        obj.style = attrValue + speed + "px";
      }
    }
  }, 30);
}
 
function getStyle(obj, attr) {
  if (obj.currentStyle) {
    return obj.currentStyle; //针对IE
  } else {
    return getComputedStyle(obj); //相对其他浏览器
  }
}
 
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 = iTarget / 100;
      clearInterval(obj.timer);
    } else {
      obj.style = (attrValue + speed) / 100;
    }
  }, 20);
}
 
function getStyle(obj, attr) {
  if (obj.currentStyle) {
    return obj.currentStyle; //针对IE
  } else {
    return getComputedStyle(obj); //相对其他浏览器
  }
}
</script>
</html>

使用js代码一个好处可以兼容低版本的IE浏览器,但是实在是太麻烦了。

使用css3比较方便,具体可以参阅css实现透明度渐变效果一章节。

js移入和离开动画方式改变透明度,这样的场景在实际项目中还是用的比较多的,关于js移入和离开动画方式改变透明度就介绍到这了。

js移入和离开动画方式改变透明度属于前端实例代码,有关更多实例代码大家可以查看

回复

我来回复
  • 暂无回复内容