DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> WEB網站前端 >> 前端技巧
兩種方法讓 IE6 正確顯示 PNG-24 透明圖片
編輯:前端技巧     

PNG-24 提供了真正的 Alpha 透明通道,但 IE6 並不支援,會在透明區域出現灰色底色。以下提供兩種解法,一個是純手寫的相容腳本,一個是使用成熟的外掛程式。

方法一:自撰 correctPNG 腳本

將以下程式碼加在 </html> 之後(透過條件註釋確保只有 IE6 會執行):

<!--[if IE 6]>
<script type="text/javascript">
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; height:" + img.height + "px;"
        + imgStyle + ";"
        + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
        + "(src='" + img.src + "', sizingMethod='scale');\"></span>";
      img.outerHTML = strNewHTML;
      i = i - 1;
    }
  }
}
correctPNG();
</script>
<![endif]-->

原理是遍歷頁面上所有 img 元素,把 PNG 換成一個 span 容器,再用 IE 私有的 AlphaImageLoader 濾鏡去繪製圖片,藉此取得真正的透明效果。

方法二:使用 DD_belatedPNG 外掛

如果不想自己維護腳本,可以直接引入社群版本:

<!--[if IE 6]>
<script src="js/DD_belatedPNG_0.0.8a.js" type="text/javascript"></script>
<script type="text/javascript">
DD_belatedPNG.fix('*');
</script>
<![endif]-->

fix('*') 代表處理頁面上所有元素;若只想處理特定範圍,可把 * 換成具体的選擇器或元素,效能會更好。

該不該花力氣做這件事

坦白說,以今天的專案條件而言,IE6 的市佔率已經低到可以忽略,這類 hack 通常不再必要。若確實有需要支援的 legacy 系統,方法二會比方法一好維護;而如果是全新專案,直接改用 SVG 或 WebP 會是更合適的選擇。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved