JavaScript透明度渐变效果

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

JavaScript透明度渐变效果属于前端实例代码,有关更多实例代码大家可以查看

建议使用CSS3实现类似功能,具体参阅CSS透明度渐变效果一章节。

下面分享一个使用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: 150px;
  height: 150px;
  background-color: #8B0000;
  float: left;
  margin: 10px;
  border: 3px solid #599;
  filter: alpha(opacity: 30);
  opacity: 0.3;
}
</style>
<script>
window.onload = function() {
  var aDiv = document.getElementsByTagName("div");
  for (var index = 0; index < aDiv.length; index++) {
    aDiv[index].timer = null;
    aDiv[index].alpha = 30;
    aDiv[index].onmouseover = function () {
      startMove(this, 100);
    }
    aDiv[index].onmouseout = function () {
      startMove(this, 30);
    }
  }
}
 
function startMove(obj, iTarget) {
 
  clearInterval(obj.timer);
 
  obj.timer = setInterval(function() {
    var speed = (iTarget - obj.alpha) / 10;
    speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
    if (obj.alpha == iTarget) {
      clearInterval(obj.timer);
    } else {
      obj.alpha += speed;
      obj.style.filter = "alpha(opacity:" + obj.alpha + ")";
      obj.style.opacity = obj.alpha / 100;
    }
  }, 30);
}
</script>
</head>
<body>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</body>
</html>

上面的代码实现了我们的要求,下面介绍一下它的实现过程。

一.代码注释:

(1).window.onload = function() {},当文档结构加载完毕再去执行函数中的代码。

(2).var aDiv = document.getElementsByTagName("div"),获取div元素集合。

(3).for (var index = 0; index < aDiv.length; index++) {},遍历集合中的每一个div元素。

(4).aDiv[index].timer = null,为当前对象添加一个自定义属性timer并赋值为null,用来作为定时器函数的标识。

(5).aDiv[index].alpha = 30,为当前对象添加一个自定义属性alpha 并赋值为30(值是经过处理的),默认透明度。

(6).aDiv[index].onmouseover = function () {

  startMove(this, 100);

},为当前元素注册onmouseover事件处理函数。

鼠标悬浮的时候,目标透明度为100,也就是不透明。

(7).aDiv[index].onmouseout = function () {

  startMove(this, 30);

},鼠标离开,透明度设置为30。

(8).function startMove(obj, iTarget) ,第一个参数是元素对象,第二个参数是目标透明度。

(9).clearInterval(obj.timer),停止上一个定时器函数的执行,防止反复移入移出导致定时器叠加的问题。

(10).obj.timer = setInterval(function() {},30),每隔30毫秒执行一次回调函数。

(11).var speed = (iTarget - obj.alpha) / 10,透明度变化幅度。

(12).speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed),将速度转换为整数。

(13). if (obj.alpha == iTarget) {

  clearInterval(obj.timer);

},如果达到目标透明度值,那么就停止定时器函数的执行。

(14).else {

  obj.alpha += speed;

obj.style.filter = "alpha(opacity:" + obj.alpha + ")";

  obj.style.opacity = obj.alpha / 100;

},设置当前元素透明度,采用了兼容性写法。

二.相关阅读:

(1).getElementsByTagName参阅document.getElementsByTagName()一章节。

(2).onmouseover事件参阅javascript mouseover事件一章节。

(3).onmouseout事件参阅javascript mouseout事件一章节。

(4).clearInterval参阅clearInterval()一章节。

(5).setInterval参阅window.setInterval()一章节。

JavaScript透明度渐变效果,这样的场景在实际项目中还是用的比较多的,关于JavaScript透明度渐变效果就介绍到这了。

回复

我来回复
  • 暂无回复内容