How To Decrease Css Opacity
I need pure javascript function that finds the current opacity of HTML element and decreases it by 10%. Is there any effective cross-browser solution? Please no JS frameworks like
Solution 1:
With IE variation
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;
}
Solution 2:
var style = document.getElementById(...).style;
style.opacity = style.opacity=='' ? 0.9 : parseFloat(style.opacity)-0.1;
The return value may need to be manually coerced into a string, I forgot.
Solution 3:
I have made this progress so far. Can you please test or finetune it?
functionnormOpacity(num,ie) {
num = parseFloat(num);
if(num<0) return0;
if(num>1 && !ie) return1;
if(num>100 && ie) return100;
return num;
}
functionchangeOpacity(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)+"";
}
usage
changeOpacity(obj,-0.1); // opacity should be 10% lower, regardless the browser
Post a Comment for "How To Decrease Css Opacity"