PNG图片色彩丰富而深受很多UI设计者的喜爱,但是在IE下对PNG图片支持得并不是很好,但是在Firefox和Opera浏览器下却是不错的。尤其是IE6下,根本显示不出来PNG透明和半透明的特性来,IE7现在已经支持了。
1、使用Javascript
好处:通吃各种浏览器www.goodsgy.com
代码如下:
|
< 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 >= 5.5) && (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>www.goodsgy.com |
www.goodsgy.com
2、使用CSS滤镜www.goodsgy.com
因为firefox等浏览器是不支持滤镜的,所以写起来会比较复杂。
|
#div1 { height: 600px; width: 260px; padding: 20px; background-repeat: repeat; }www.goodsgy.com
/* for ie7 ff*/ html>body #div1 { background:url(../images/menu1.png) no-repeat; } /* for ie6 */ * #div1 { background:none; filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='images/menu1.png', sizingMethod='crop'); }www.goodsgy.com |
www.goodsgy.com
需要注意的是:AlphaImageLoader滤镜会导致该区域的链接和按钮无效,解决的办法是为链接或按钮添加:position: relative;这样条代码,使其相对浮动。AlphaImageLoader无法设置背景的重复,所以对图片的切图精度会有很高的精确度要求。 www.goodsgy.com
3、使用CSS滤镜和hack
|
html>body .png { background:url(1.png); width:300px; height:100px; border:#000 solid 1px;}www.goodsgy.com
/* ie6 */* html .png { filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=scale, src='1.png'); background:none; width:300px; height:100px; border:#000 solid 1px;}www.goodsgy.com |
www.goodsgy.com