如果有可能建议使用css3实现类似功能,具体可以参阅css实现透明度渐变效果一章节。 下面分享一个使用js实现的此功能,兼容性更好一些,代码实例如下:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
<!doctype html>
<
html
>
<
head
>
<
meta
charset
=
"utf-8"
>
<
title
>js实现透明度渐变效果</
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; },设置当前元素透明度,采用了兼容性写法。 |