我需要纯javascript函数来查找HTML元素的当前不透明度并将其减少10%。有没有有效的跨浏览器解决方案?
请不要像jQuery这样的JS框架(我有我的理由所以不要问为什么),谢谢。
答案 0 :(得分:1)
使用IE变体
var style = document.getElementById(...).style;
if(browserIsIE) {
var regExpResult = /alpha\(opacity\s*=\s*(\d*)\s*\)/.exec(style.filter);
var opacity;
if(regExpResult && regExpResult.constructor == Array && regExpResult[1] && opacity = parseInt(regExpResult[1])) {
style.filter = "alpha(opacity = " + (opacity - 10) + ")";
} else {
style.filter = "alpha(opacity = 90)";
}
} else {
style.opacity = style.opacity=='' ? 0.9 : parseFloat(style.opacity)-0.1;
}
答案 1 :(得分:0)
var style = document.getElementById(...).style;
style.opacity = style.opacity=='' ? 0.9 : parseFloat(style.opacity)-0.1;
返回值可能需要手动强制转换为字符串,我忘了。
答案 2 :(得分:0)
到目前为止,我已取得这一进展。你可以测试一下吗?
function normOpacity(num,ie) {
num = parseFloat(num);
if(num<0) return 0;
if(num>1 && !ie) return 1;
if(num>100 && ie) return 100;
return num;
}
function changeOpacity(obj,diff) {
if(!obj) return;
if(!obj.filters) {
var gcs = document.defaultView.getComputedStyle(obj,null);
var op = parseFloat(gcs.getPropertyValue("opacity")) + diff;
return obj.style.opacity = normOpacity(op)+"";
}
if(!obj.style.zoom) obj.style.zoom = 1;
var op, al, dx = "DXImageTransform.Microsoft.";
try { al = obj.filters.item(dx+"Alpha"); } catch(e) {}
if(!al) try { al = obj.filters.item("Alpha"); } catch(e) {}
if(!al) {
var op = normOpacity(100+100*diff,true);
return obj.style.filter+= "progid:"+dx+"Alpha(opacity="+op+")";
}
try { op = al["Opacity"]; } catch(e) { op = 100; }
al["Opacity"] = normOpacity(parseInt(op)+100*diff,true)+"";
}
使用
changeOpacity(obj,-0.1); // opacity should be 10% lower, regardless the browser