javascript - trick to manipulate the opacity

本文介绍了如何在不同浏览器中实现透明度效果,通过使用通用的CSS属性和针对IE的专有滤镜来确保跨浏览器的一致性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

All other browsre may have supported the opacity CSS property whereas Internext explorer use its properietary alpha filter.

 

opacity: 0.5;
filter: alpha(opacity=50);

 

where opacity notation is for all other browsers, and filter is for IE.

 

so the following code shows how you can do a cross browser opacity

 

<html>
<head>
<title>Opacity Style Test</title>
<script type="text/javascript">
  (function () {
    var div = document.createElement("div");
    div.innerHTML = "<div style='opacity:.5;'></div>";
    // If .5 becomes 0.5, we assume the browser knows how
    // to handle native opacity
    var native = div.firstChild.style.opacity === "0.5";
    this.opacityStyle = function (elem, value) {
      if (typeof value !== "undefined") {
        if (native) {
          elem.style.opacity = value;
        } else {
          // .filter may not exist
          elem.style.filter = (elem.style.filter || "")
                    // Need to replace any existing alpha
          .replace(/alpha\([^)]*\)/, "") +
                    // If we have a number, set that as the value (0-100)
          (parseFloat(value) + '' == "NaN" ?
            "" :
            "alpha(opacity=" + value * 100 + ")");
        }
        elem.style[floatName] = value;
      }
      if (native) {
        return elem.style.opacity;
      } else {
        // Only attempt to get a value if one might exist
        var match = elem.style.filter.match(/opacity=([^)]*)/);
        return match ?
          (parseFloat(match[1]) / 100) + "" :
          "";
      }
    };
  })();
  window.onload = function () {
    var div = document.getElementById("div");
    // Alerts out '0.5'
    alert(opacityStyle(div));
  };
</script>
</head>
<body>
<div style="opacity:0.5;filter:alpha(opacity=50);" id="div"></div>
</body>
</html>
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值