png 透明針對 IE6 一直是件挺麻煩的事情,使用的方法也是各有不同,大多的原理是用 IE 的濾鏡來解決的。
文法:
filter : progid:DXImageTransform.Microsoft.AlphaImageLoader ( enabled=bEnabled , sizingMethod=sSize , src=sURL )
enabled : 可選項。布爾值 (Boolean) 。設定或檢索濾鏡是否激活。 true | false true : 預設值。濾鏡激活。
false : 濾鏡被禁止。
sizingMethod : 可選項。字元串 (String) 。設定或檢索濾鏡作用的對象的圖檔在對象容器邊界内的顯示方式。 crop : 剪切圖檔以适應對象尺寸。
image : 預設值。增大或減小對象的尺寸邊界以适應圖檔的尺寸。 scale : 縮放圖檔以适應對象的尺寸邊界。
src : 必選項。字元串 (String) 。使用絕對或相對 url 位址指定背景圖像。假如忽略此參數,濾鏡将不會作用。
現在一般在使用的方法有一下幾種:
1 、 css 方法
css :
.pngs {
height: 90px;width: 90px;
background-image:url(icon_home.png)!important; /* FF IE7 */
background-repeat:no-repeat;
_filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=’icon_home.png’); /* IE6 */
_ background-image: none; /* IE6 */
}
用了 ie 的濾鏡就是這樣麻煩
隻要在用到濾鏡 filter 内的 a 連結樣式上加上 position:relative; 連結就可以生效了
xhtml :
<div class= ” pngs ” ></div>
這種方法的優點就是使用簡單友善,但是不能作為背景,且隻能用作單個 png 圖檔的使用。如果要作為背景,需要新增加一個 div 層,并設定其 position:relative;
css
.png div{position:relative;}
xhml:
<div class=’png’>
<div>
CSS 背景PNG透明 及 連結失效問題解決
</div>
</div>
這種方法可以使用在那些 png 圖檔不多,且不需要 repeat 的情況下。
2 、 js 方法
<script language=”JavaScript”>
function correctPNG() // correctly handle PNG transparency in Win IE 5.5 & 6.
{
var arVersion = navigator.appVersion.split(“MSIE”)
var version = parseFloat(arVersion[1])
if ((version == 6.0) && (document.body.filters))
{
for(var j=0; j<document.images.length; j++)
{
var img = document.images[j]
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
j = j-1
}
}
}
}
window.attachEvent(“onload”, correctPNG);
</script>
這種 js 先判斷是否 IE ,然後判斷 ie 版本,版本在 6.0 下則判定函數,給 png 的圖檔添加濾鏡。
使用起來的确友善,無論多少圖檔都可以解決,但是依然無法 repeat 。
3 、 htc 方法
htc 相當于完全通過插件的方法修複的 IE6 的 bug ,功能強大,支援 repeat ,背景等功能,使用起來也很友善。
使用一個 iepngfix.htc 檔案,和一個透明的 gif 檔案。
使用方法:
<! – [if lte IE 6]>
<style>.png{behavior:url( “ jscss/iepngfix.htc ” );}</style> // 在這裡可以加入其他用到 png 圖檔的 id 或者 class
<script type= ” text/javascript ” src= ” jscss/iepngfix_tilebg.js ” ></script>
<![endif] – >
ps :如果需要 repeat 背景,往往需要設定這個 div 寬度為 100% 。
使用見: http://qqgame.qq.com/act/a20091210prize4/index.htm ,在其中有 iepngfix.htc 可下載下傳。
總結這幾種方法,第三種方法是最簡單使用,且容易推廣的方法,建議可以做個公共的位址,有産品需要,隻需要應用這個公共位址就行了。