How to decrease CSS opacity

[亡魂溺海] 提交于 2019-12-13 04:03:41

问题


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 jQuery (I have my reasons so do not ask why), thanks.


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



回答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.




回答3:


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


来源:https://stackoverflow.com/questions/6235227/how-to-decrease-css-opacity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!