怎樣使用透明的PNG圖片在IE瀏覽器中變得透明?

來源:互聯網
上載者:User

平常,我們經常使用Gif格式的圖片以保持圖片在瀏覽器中透明,以支援底色。但由於IE瀏覽器本身的原因,我們無法使透明的PNG圖片透明起來,我們經常會看到這樣的效果:

這張圖片在圖形製作軟體比如PHOTOSHOP,Fireworks等上面查看都是透明的,但在IE瀏覽器中就變得不透明了,有一層灰灰的底色,是不是很難看?

那麼,如何將它在IE瀏覽器下變得透明呢?

首先看我們的<img>標籤代碼:
<img src="Example.png" border="0" alt="放大鏡" />

我們的目標是......?(沒有蛀牙?)不,我們的目標是將它透明,並使之也要保持其他屬性,比如alt提示。

我們將利用IE中特有的特效來滿足這個要求,這就是AlphaImageLoader Filter (http://msdn.microsoft.com/library/default.asp?url=/workshop/author/filter/reference/filters/alphaimageloader.asp)

如何做?
將下面代碼儲存為correctPNG.js:

function correctPNG()
   {
   for(var i=0; i<document.images.length; i++)
      {
   var img = document.images[i]
   var imgName = img.src.toUpperCase()
   if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
      {
   var imgID = (img.id) ? "id='" + img.id + "' " : ""
   var imgClass = (img.className) ? "class='" + img.className + "' " : ""
   var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
   var imgStyle = "display:inline-block;" + img.style.cssText
   if (img.align == "left") imgStyle = "float:left;" + imgStyle
   if (img.align == "right") imgStyle = "float:right;" + imgStyle
   if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle  
   var strNewHTML = "<span " + imgID + imgClass + imgTitle
   + " style=/"" + "width:" + img.width + "px; margin:6px; height:" + img.height + "px;" + imgStyle + ";"
      + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
   + "(src=/'" + img.src + "/', sizingMethod='scale');/"></span>"
   img.outerHTML = strNewHTML
   i = i-1
      }
      }
   }
window.attachEvent("onload", correctPNG);

然後在你需要透明的網頁中的<head>....</head>區加入:<script type="text/javascript" src="correctPNG.js"></script>

在<body>區加入多個與<img src="Example.png" border="0" alt="放大鏡" />類似的PNG圖片,試試看?
這是效果:

OK。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.