js里面设置DOM节点透明度的函数属性:filter= "alpha(opacity=" + value+ ")"(兼容ie)和opacity=value/100(兼容FF和GG)。
先来看看设置透明度的兼容性代码:
function setOpacity(ele, opacity) {
if (ele.style.opacity != undefined) {
///兼容FF和GG和新版本IE
ele.style.opacity = opacity / 100;
} else {
///兼容老版本ie
ele.style.filter = "alpha(opacity=" + opacity + ")";
}
}
关于有的小伙伴这样写:
function setOpacity(ele, opacity) {
if (document.all) {
///兼容ie
ele.style.filter = "alpha(opacity=" + opacity + ")";
}
ele {
///兼容FF和GG
ele.style.opacity = opacity / 100;
}
}
我想说这样在IE10下运行有问题,点了之后没反应。因为IE10支持opacity属性不支持filter了,这个方法不可取。
fadein 函数代码:
function fadein(ele, opacity, speed) {
if (ele) {
var v = ele.style.filter.replace("alpha(opacity=", "").replace(")", "") || ele.style.opacity;
v var count = speed / 1000;
var avg = count var timer = null;
timer = setInterval(function() {
if (v v += avg;
setOpacity(ele, v);
} else {
clearInterval(timer);
}
}, 500);
}
}
fadeout 函数代码:
function fadeout(ele, opacity, speed) {
if (ele) {
var v = ele.style.filter.replace("alpha(opacity=", "").replace(")", "") || ele.style.opacity || 100;
v var count = speed / 1000;
var avg = (100 - opacity) / count;
var timer = null;
timer = setInterval(function() {
if (v - avg > opacity) {
v -= avg;
setOpacity(ele, v);
} else {
clearInterval(timer);
}
}, 500);
}
}
下面给一个demo示例:
有什么更好的实现方式可以留言。。。