IE6透明PNG解决方案

IE6不支持PNG-24图片一直困扰很多人,但是可以通过IE的独有的滤镜来解决,解决的方案很多,比如:将滤镜写在CSS里,还可以写成单独的 Javascript文件,本来认为推荐两种做法:第一种,将所有PNG图片添加滤镜(此方法有副作用);第二种:有选择性的添加滤镜(推荐);两者都可 以将代码放在单独的JS文件里,然后引用。

 

第一种:

直接添加如下代码:

JSCode

 1 function correctPNG() {
 2     for (var i = 0; i < document.images.length; i++) {
 3         var img = document.images[i];
 4         var imgName = img.src.toUpperCase();
 5         if (imgName.substring(imgName.length - 3, imgName.length) == "PNG") {
 6             var imgID = (img.id) ? "id='" + img.id + "' " : "";
 7             var imgClass = (img.className) ? "class='" + img.className + "' " : "";
 8             var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' ";
 9             var imgStyle = "display:inline-block;" + img.style.cssText;
10             if (img.align == "left") {
11                 imgStyle = "float:left;" + imgStyle;
12             }
13             if (img.align == "right") {
14                 imgStyle = "float:right;" + imgStyle;
15             }
16             if (img.parentElement.href) {
17                 imgStyle = "cursor:hand;" + imgStyle;
18             }
19             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>";
20             img.outerHTML = strNewHTML;
21             i = i - 1;
22         }
23     }
24 }
25 function alphaBackgrounds() {
26     var rslt = navigator.appVersion.match(/MSIE(d+.d+)/, '');
27     var itsAllGood = (rslt !== null && Number(rslt[1]) >= 5.5);
28     for (i = 0; i < document.all.length; i++) {
29         var bg = document.all[i].currentStyle.backgroundImage;
30         if (bg) {
31             if (bg.match(/.png/i) !== null) {
32                 var mypng = bg.substring(5, bg.length - 2);
33                 document.all[i].style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src ='" +
34                     mypng + "',sizingMethod='crop')";
35                 document.all[i].style.backgroundImage = "url('')";
36             }
37         }
38     }
39 }
40 if (navigator.userAgent.indexOf("MSIE 6.0") > -1) {
41     window.attachEvent("onload", correctPNG);
42     window.attachEvent("onload", alphaBackgrounds);
43 }
View Code

 

第二种:

1)添加以下代码:

JSCode 

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

 

2)第二步在调用:

1     <!--[if IE 6]>     
2     <script src="js/DD_belatedPNG.js" mce_src="DD_belatedPNG.js"></script>     
3     <script type="text/javascript">       
4      DD_belatedPNG.fix('.class');//这里是CSS选择,多个就有分号“,”隔开;  
5      如:DD_belatedPNG.fix('.class1,.class2,.class3')  
6     </script>   
7     <![endif]-->  

 第二种方法使用得比较多,可以根据需要选择滤镜,不会影响其它图片,副作用小。

虽然可以使用滤镜来解决透明的问题,但是这也是有条件的,所使用的图片不能 background-position: 与background-repeat,所以不能从根本解决问题,不过基本可以满足大部分需求了。

 

posted @ 2013-09-23 14:38  kingwell  阅读(382)  评论(0编辑  收藏  举报