| 版本 | PNG 支持 | 主要問題 |
|---|---|---|
| IE6 | ❌ 不支持透明 | 透明區域顯示灰藍背景 |
| IE7/8 | ⚠️ 部分支持 | 動態修改透明度/位置時出現黑邊/黑塊 |
| IE9+ | ✅ 完美支持 | 無 |
原理:將 `` 替換為 ``,用 CSS 濾鏡加載 PNG,濾鏡原生支持透明通道。
` 前,需 jQuery 1.8+)
<script>
function correctPNG() {
// 僅 IE5.5-8 執行
if (!(!window.addEventListener && !document.getElementsByClassName)) return;
var imgs = document.images;
for (var i = 0; i < imgs.length; i++) {
var img = imgs[i];
var src = img.src.toUpperCase();
if (src.substring(src.length - 3) === "PNG" && !img.getAttribute("usemap")) {
var id = img.id || 'png_' + i;
var style = "display:inline-block;" + img.style.cssText;
if (img.align === "left") style = "float:left;" + style;
if (img.align === "right") style = "float:right;" + style;
if (img.parentElement.href) style = "cursor:pointer;" + style;
var span = document.createElement("span");
span.id = id;
span.className = img.className;
span.title = img.title || img.alt;
span.style.cssText = "width:" + img.width + "px;height:" + img.height + "px;" + style +
"filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + img.src + "', sizingMethod='scale');";
img.parentNode.replaceChild(span, img);
i--; // 因為替換後數組長度變化
}
}
}
// 掛載到 window.onload
if (!window.addEventListener) window.attachEvent("onload", correctPNG);
</script>
修正後 `` 變為 ``,直接操作原圖片選擇器失效。
<div id="wrap"><img src="icon.png"></div>
<script>
$("#wrap").animate({opacity:0.2, marginLeft:500}, 1000); // 操作包裹層
</script>
<div id="wrap"><img src="icon.png"></div>
<script>
// 兼容選擇器:修正後找 span,未修正找 img
var target = $("#wrap span")[0] || $("#wrap img")[0];
$(target).animate({opacity:0.2, marginLeft:500, width:'500px', height:'500px'}, 1000);
</script>
.png-wrapper {
width: 60px; height: 21px;
position: absolute; bottom: 8px; left: 0; z-index: 1;
margin: 0 auto; display: block;
background: #FAFDEF; /* 關鍵:背景色 */
zoom: 1; /* 關鍵:觸發 hasLayout */
}
IE6/7/8 市場份額已極低(<0.5%),**建議優雅降級**:現代瀏覽器正常顯示 PNG,舊 IE 顯示降級圖(GIF/JPG)或忽略透明效果,通過條件註釋或 `@supports` 區分。若必須支持,推薦使用成熟庫 DD_belatedPNG 或 **IE8.js**,而非手工維護濾鏡腳本。