1. 原理
IE6默认不支持PNG图片的半透明效果, 但由于它是XP系统默认的浏览器,目前仍被广泛的使用. 解决此问题的方法是在Html中加入Javascript, 其中判断当浏览器是低版本IE时对Html中的PNG做相应处理.
2. 代码
只需在Html开头加入以下Javascript脚本即可
<scriptlanguage="JavaScript">
function correctPNG() // correctly handlePNG transparency in Win IE 5.5 & 6.
{
var arVersion =navigator.appVersion.split("MSIE")
var version = parseFloat(arVersion[1])
if ((version >= 5.5) &&(document.body.filters))
{
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
}
}
}
}
window.attachEvent("onload",correctPNG);
</script>
3. 示例
具体效果见网页
http://oatmental123.sinaapp.com/slim/
通过在Firefox浏览器中点右键, 查看网页源代码, 可参考其具体代码.