IE6中 PNG 背景透明的最佳解决方案

为什么要使用 PNG 图片?

简单来说,使用 PNG 格式比起 GIF 来表现色彩更丰富,特别是表现渐变以及背景透明的渐变要比GIF格式出色很多。目前,最新的浏览器基本上都支持PNG格式。唯独有万恶的 IE6 不支持 PNG 背景透明,在 IE6 中的 PNG 背景图会显示一个灰色的背景。

IE6 中 PNG 背景图片透明的方法

其实方法有很多,但网络上提供的方法也有诸多缺陷。比如不支持 css 中 backgrond-position 与 background-repeat 等,所以园子推荐你使用 DD_belatedPNG,方法如下:

1.首先下载 DD_belatedPNG.js 文件,本文下方有提供下载,将此文件放置到你的网站中的 js 目录下。

2.在你使用了 PNG 背景的页面头部嵌入以下代码,一般是加在 head 区域。

1
2
3
4
5
6
7
8
<!--[if IE 6]>   
<script src="js/DD_belatedPNG.js" mce_src="DD_belatedPNG.js"></script>   
<script type="text/javascript">     
 /* EXAMPLE */   
 DD_belatedPNG.fix('.png_bg');   
/* 将 .png_bg 改成你应用了透明PNG的CSS选择器,例如我例子中的'.trans'*/   
</script> 
<![endif]-->

需要注意的一些问题:

1.如果你放置的 DD_belatedPNG.js 路径不同的话,也需要更改上述代码中的路径。

2.以上代码中的

1
DD_belatedPNG.fix('.png_bg');

括号中的 .png_bg 改成你在 CSS 定义了 PNG 背景图片的选择器,多个选择器请用英文逗号隔开,如下行代码所示:

1
DD_belatedPNG.fix('.png_bg1, .png_bg2');

3.有些朋友可能需要用到透明的 PNG 图片做为鼠标经过时的背景图片,这就需要用到 a:hover 属性,在这种情况下就需要以“a:hover”来做选择器了,你可以参考下面代码的写法:

1
2
3
4
5
6
<!--[if IE 6]>   
<script type="text/javascript" src="js/DD_belatedPNG.js" ></script>   
<script type="text/javascript">
DD_belatedPNG.fix('.trans,.box a:hover');   
</script>   
<![endif]-->

下面是DD_belatedPNG.js修正了一些IE6BUG的代码:

  1 /**
  2 * DD_belatedPNG: Adds IE6 support: PNG images for CSS background-image and HTML <IMG/>.
  3 * Author: Drew Diller
  4 * Email: drew.diller@gmail.com
  5 * URL: http://www.dillerdesign.com/experiment/DD_belatedPNG/
  6 * Version: 0.0.8a
  7 * Licensed under the MIT License: http://dillerdesign.com/experiment/DD_belatedPNG/#license
  8 *
  9 * Example usage:
 10 * DD_belatedPNG.fix('.png_bg'); // argument is a CSS selector
 11 * DD_belatedPNG.fixPng( someNode ); // argument is an HTMLDomElement
 12 **/
 13 
 14 /*
 15 PLEASE READ:
 16 Absolutely everything in this script is SILLY.  I know this.  IE's rendering of certain pixels doesn't make sense, so neither does this code!
 17 */
 18 
 19 var DD_belatedPNG = {
 20     ns: 'DD_belatedPNG',
 21     imgSize: {},
 22     delay: 10,
 23     nodesFixed: 0,
 24     createVmlNameSpace: function () { /* enable VML */
 25         if (document.namespaces && !document.namespaces[this.ns]) {
 26             document.namespaces.add(this.ns, 'urn:schemas-microsoft-com:vml');
 27         }
 28     },
 29     createVmlStyleSheet: function () { /* style VML, enable behaviors */
 30         /*
 31             Just in case lots of other developers have added
 32             lots of other stylesheets using document.createStyleSheet
 33             and hit the 31-limit mark, let's not use that method!
 34             further reading: http://msdn.microsoft.com/en-us/library/ms531194(VS.85).aspx
 35         */
 36         var screenStyleSheet, printStyleSheet;
 37         screenStyleSheet = document.createElement('style');
 38         screenStyleSheet.setAttribute('media', 'screen');
 39         document.documentElement.firstChild.insertBefore(screenStyleSheet, document.documentElement.firstChild.firstChild);
 40         if (screenStyleSheet.styleSheet) {
 41             screenStyleSheet = screenStyleSheet.styleSheet;
 42             screenStyleSheet.addRule(this.ns + '\:*', '{behavior:url(#default#VML)}');
 43             screenStyleSheet.addRule(this.ns + '\:shape', 'position:absolute;');
 44             screenStyleSheet.addRule('img.' + this.ns + '_sizeFinder', 'behavior:none; border:none; position:absolute; z-index:-1; top:-10000px; visibility:hidden;'); /* large negative top value for avoiding vertical scrollbars for large images, suggested by James O'Brien, http://www.thanatopsic.org/hendrik/ */
 45             this.screenStyleSheet = screenStyleSheet;
 46             
 47             /* Add a print-media stylesheet, for preventing VML artifacts from showing up in print (including preview). */
 48             /* Thanks to R閙i Pr関ost for automating this! */
 49             printStyleSheet = document.createElement('style');
 50             printStyleSheet.setAttribute('media', 'print');
 51             document.documentElement.firstChild.insertBefore(printStyleSheet, document.documentElement.firstChild.firstChild);
 52             printStyleSheet = printStyleSheet.styleSheet;
 53             printStyleSheet.addRule(this.ns + '\:*', '{display: none !important;}');
 54             printStyleSheet.addRule('img.' + this.ns + '_sizeFinder', '{display: none !important;}');
 55         }
 56     },
 57     readPropertyChange: function () {
 58         var el, display, v;
 59         el = event.srcElement;
 60         if (!el.vmlInitiated) {
 61             return;
 62         }
 63         if (event.propertyName.search('background') != -1 || event.propertyName.search('border') != -1) {
 64             DD_belatedPNG.applyVML(el);
 65         }
 66         if (event.propertyName == 'style.display') {
 67             display = (el.currentStyle.display == 'none') ? 'none' : 'block';
 68             for (v in el.vml) {
 69                 if (el.vml.hasOwnProperty(v)) {
 70                     el.vml[v].shape.style.display = display;
 71                 }
 72             }
 73         }
 74         if (event.propertyName.search('filter') != -1) {
 75             DD_belatedPNG.vmlOpacity(el);
 76         }
 77     },
 78     vmlOpacity: function (el) {
 79         if (el.currentStyle.filter.search('lpha') != -1) {
 80             var trans = el.currentStyle.filter;
 81             trans = parseInt(trans.substring(trans.lastIndexOf('=')+1, trans.lastIndexOf(')')), 10)/100;
 82             el.vml.color.shape.style.filter = el.currentStyle.filter; /* complete guesswork */
 83             el.vml.image.fill.opacity = trans; /* complete guesswork */
 84         }
 85     },
 86     handlePseudoHover: function (el) {
 87         setTimeout(function () { /* wouldn't work as intended without setTimeout */
 88             DD_belatedPNG.applyVML(el);
 89         }, 1);
 90     },
 91     /**
 92     * This is the method to use in a document.
 93     * @param {String} selector - REQUIRED - a CSS selector, such as '#doc .container'
 94     **/
 95     fix: function (selector) {
 96         if (this.screenStyleSheet) {
 97             var selectors, i;
 98             selectors = selector.split(','); /* multiple selectors supported, no need for multiple calls to this anymore */
 99             for (i=0; i<selectors.length; i++) {
100                 this.screenStyleSheet.addRule(selectors[i], 'behavior:expression(DD_belatedPNG.fixPng(this))'); /* seems to execute the function without adding it to the stylesheet - interesting... */
101             }
102         }
103     },
104     applyVML: function (el) {
105         el.runtimeStyle.cssText = '';
106         this.vmlFill(el);
107         this.vmlOffsets(el);
108         this.vmlOpacity(el);
109         if (el.isImg) {
110             this.copyImageBorders(el);
111         }
112     },
113     attachHandlers: function (el) {
114         var self, handlers, handler, moreForAs, a, h;
115         self = this;
116         handlers = {resize: 'vmlOffsets', move: 'vmlOffsets'};
117         if (el.nodeName == 'A') {
118             moreForAs = {mouseleave: 'handlePseudoHover', mouseenter: 'handlePseudoHover', focus: 'handlePseudoHover', blur: 'handlePseudoHover'};
119             for (a in moreForAs) {            
120                 if (moreForAs.hasOwnProperty(a)) {
121                     handlers[a] = moreForAs[a];
122                 }
123             }
124         }
125         for (h in handlers) {
126             if (handlers.hasOwnProperty(h)) {
127                 handler = function () {
128                     self[handlers[h]](el);
129                 };
130                 el.attachEvent('on' + h, handler);
131             }
132         }
133         el.attachEvent('onpropertychange', this.readPropertyChange);
134     },
135     giveLayout: function (el) {
136          el.style.zoom = 1;
137                 if (el.currentStyle.position == 'static') {
138                 var tags=el.nodeName.toLowerCase();
139                 if(tags!='html' && tags!='a'&& tags!='img'){
140                     el.style.position = 'relative'
141                     };
142             }
143     },
144     copyImageBorders: function (el) {
145         var styles, s;
146         styles = {'borderStyle':true, 'borderWidth':true, 'borderColor':true};
147         for (s in styles) {
148             if (styles.hasOwnProperty(s)) {
149                 el.vml.color.shape.style[s] = el.currentStyle[s];
150             }
151         }
152     },
153     vmlFill: function (el) {
154         if (!el.currentStyle) {
155             return;
156         } else {
157             var elStyle, noImg, lib, v, img, imgLoaded;
158             elStyle = el.currentStyle;
159         }
160         for (v in el.vml) {
161             if (el.vml.hasOwnProperty(v)) {
162                 el.vml[v].shape.style.zIndex = elStyle.zIndex;
163             }
164         }
165         el.runtimeStyle.backgroundColor = '';
166         el.runtimeStyle.backgroundImage = '';
167         noImg = true;
168         if (elStyle.backgroundImage != 'none' || el.isImg) {
169             if (!el.isImg) {
170                 el.vmlBg = elStyle.backgroundImage;
171                 el.vmlBg = el.vmlBg.substr(5, el.vmlBg.lastIndexOf('")')-5);
172             }
173             else {
174                 el.vmlBg = el.src;
175             }
176             lib = this;
177             if (!lib.imgSize[el.vmlBg]) { /* determine size of loaded image */
178                 img = document.createElement('img');
179                 lib.imgSize[el.vmlBg] = img;
180                 img.className = lib.ns + '_sizeFinder';
181                 img.runtimeStyle.cssText = 'behavior:none; position:absolute; left:-10000px; top:-10000px; border:none; margin:0; padding:0;'; /* make sure to set behavior to none to prevent accidental matching of the helper elements! */
182                 imgLoaded = function () {
183                     this.width = this.offsetWidth; /* weird cache-busting requirement! */
184                     this.height = this.offsetHeight;
185                     lib.vmlOffsets(el);
186                 };
187                 img.attachEvent('onload', imgLoaded);
188                 img.src = el.vmlBg;
189                 img.removeAttribute('width');
190                 img.removeAttribute('height');
191                 document.body.insertBefore(img, document.body.firstChild);
192             }
193             el.vml.image.fill.src = el.vmlBg;
194             noImg = false;
195         }
196         el.vml.image.fill.on = !noImg;
197         el.vml.image.fill.color = 'none';
198         el.vml.color.shape.style.backgroundColor = elStyle.backgroundColor;
199         el.runtimeStyle.backgroundImage = 'none';
200         el.runtimeStyle.backgroundColor = 'transparent';
201     },
202     /* IE can't figure out what do when the offsetLeft and the clientLeft add up to 1, and the VML ends up getting fuzzy... so we have to push/enlarge things by 1 pixel and then clip off the excess */
203     vmlOffsets: function (el) {
204         var thisStyle, size, fudge, makeVisible, bg, bgR, dC, altC, b, c, v;
205         thisStyle = el.currentStyle;
206         size = {'W':el.clientWidth+1, 'H':el.clientHeight+1, 'w':this.imgSize[el.vmlBg].width, 'h':this.imgSize[el.vmlBg].height, 'L':el.offsetLeft, 'T':el.offsetTop, 'bLW':el.clientLeft, 'bTW':el.clientTop};
207         fudge = (size.L + size.bLW == 1) ? 1 : 0;
208         /* vml shape, left, top, width, height, origin */
209         makeVisible = function (vml, l, t, w, h, o) {
210             vml.coordsize = w+','+h;
211             vml.coordorigin = o+','+o;
212             vml.path = 'm0,0l'+w+',0l'+w+','+h+'l0,'+h+' xe';
213             vml.style.width = w + 'px';
214             vml.style.height = h + 'px';
215             vml.style.left = l + 'px';
216             vml.style.top = t + 'px';
217         };
218         makeVisible(el.vml.color.shape, (size.L + (el.isImg ? 0 : size.bLW)), (size.T + (el.isImg ? 0 : size.bTW)), (size.W-1), (size.H-1), 0);
219         makeVisible(el.vml.image.shape, (size.L + size.bLW), (size.T + size.bTW), (size.W), (size.H), 1 );
220         bg = {'X':0, 'Y':0};
221         if (el.isImg) {
222             bg.X = parseInt(thisStyle.paddingLeft, 10) + 1;
223             bg.Y = parseInt(thisStyle.paddingTop, 10) + 1;
224         }
225         else {
226             for (b in bg) {
227                 if (bg.hasOwnProperty(b)) {
228                     this.figurePercentage(bg, size, b, thisStyle['backgroundPosition'+b]);
229                 }
230             }
231         }
232         el.vml.image.fill.position = (bg.X/size.W) + ',' + (bg.Y/size.H);
233         bgR = thisStyle.backgroundRepeat;
234         dC = {'T':1, 'R':size.W+fudge, 'B':size.H, 'L':1+fudge}; /* these are defaults for repeat of any kind */
235         altC = { 'X': {'b1': 'L', 'b2': 'R', 'd': 'W'}, 'Y': {'b1': 'T', 'b2': 'B', 'd': 'H'} };
236         if (bgR != 'repeat' || el.isImg) {
237             c = {'T':(bg.Y), 'R':(bg.X+size.w), 'B':(bg.Y+size.h), 'L':(bg.X)}; /* these are defaults for no-repeat - clips down to the image location */
238             if (bgR.search('repeat-') != -1) { /* now let's revert to dC for repeat-x or repeat-y */
239                 v = bgR.split('repeat-')[1].toUpperCase();
240                 c[altC[v].b1] = 1;
241                 c[altC[v].b2] = size[altC[v].d];
242             }
243             if (c.B > size.H) {
244                 c.B = size.H;
245             }
246             el.vml.image.shape.style.clip = 'rect('+c.T+'px '+(c.R+fudge)+'px '+c.B+'px '+(c.L+fudge)+'px)';
247         }
248         else {
249             el.vml.image.shape.style.clip = 'rect('+dC.T+'px '+dC.R+'px '+dC.B+'px '+dC.L+'px)';
250         }
251     },
252     figurePercentage: function (bg, size, axis, position) {
253         var horizontal, fraction;
254         fraction = true;
255         horizontal = (axis == 'X');
256         switch(position) {
257             case 'left':
258             case 'top':
259                 bg[axis] = 0;
260                 break;
261             case 'center':
262                 bg[axis] = 0.5;
263                 break;
264             case 'right':
265             case 'bottom':
266                 bg[axis] = 1;
267                 break;
268             default:
269                 if (position.search('%') != -1) {
270                     bg[axis] = parseInt(position, 10) / 100;
271                 }
272                 else {
273                     fraction = false;
274                 }
275         }
276         bg[axis] = Math.ceil(  fraction ? ( (size[horizontal?'W': 'H'] * bg[axis]) - (size[horizontal?'w': 'h'] * bg[axis]) ) : parseInt(position, 10)  );
277         if (bg[axis] % 2 === 0) {
278             bg[axis]++;
279         }
280         return bg[axis];
281     },
282     fixPng: function (el) {
283         el.style.behavior = 'none';
284         var lib, els, nodeStr, v, e;
285         if (el.nodeName == 'BODY' || el.nodeName == 'TD' || el.nodeName == 'TR') { /* elements not supported yet */
286             return;
287         }
288         el.isImg = false;
289         if (el.nodeName == 'IMG') {
290             if(/.png(?:W|$)/.test(el.src.toLowerCase())) {
291                                 el.isImg = true;
292                                 el.style.visibility = 'hidden';
293             }
294             else {
295                 return;
296             }
297         }
298         else if (el.currentStyle.backgroundImage.toLowerCase().search('.png') == -1) {
299             return;
300         }
301         lib = DD_belatedPNG;
302         el.vml = {color: {}, image: {}};
303         els = {shape: {}, fill: {}};
304         for (v in el.vml) {
305             if (el.vml.hasOwnProperty(v)) {
306                 for (e in els) {
307                     if (els.hasOwnProperty(e)) {
308                         nodeStr = lib.ns + ':' + e;
309                         el.vml[v][e] = document.createElement(nodeStr);
310                     }
311                 }
312                 el.vml[v].shape.stroked = false;
313                 el.vml[v].shape.appendChild(el.vml[v].fill);
314                 el.parentNode.insertBefore(el.vml[v].shape, el);
315             }
316         }
317         el.vml.image.shape.fillcolor = 'none'; /* Don't show blank white shapeangle when waiting for image to load. */
318         el.vml.image.fill.type = 'tile'; /* Makes image show up. */
319         el.vml.color.fill.on = false; /* Actually going to apply vml element's style.backgroundColor, so hide the whiteness. */
320         lib.attachHandlers(el);
321         lib.giveLayout(el);
322         lib.giveLayout(el.offsetParent);
323         el.vmlInitiated = true;
324         lib.applyVML(el); /* Render! */
325     }
326 };
327 try {
328     document.execCommand("BackgroundImageCache", false, true); /* TredoSoft Multiple IE doesn't like this, so try{} it */
329 } catch(r) {}
330 DD_belatedPNG.createVmlNameSpace();
331 DD_belatedPNG.createVmlStyleSheet();
原文地址:https://www.cnblogs.com/zimin1985/p/3371731.html