开发者

How to decrease CSS opacity

I need pure javascript function that f开发者_JAVA技巧inds the current opacity of HTML element and decreases it by 10%. Is there any effective cross-browser solution?

Please no JS frameworks like jQuery (I have my reasons so do not ask why), thanks.


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;
}


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.


I have made this progress so far. Can you please test or finetune it?

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)+"";
}

usage

changeOpacity(obj,-0.1); // opacity should be 10% lower, regardless the browser
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜