2025年3月15日 星期六
easyie调整ie6,ie7,ie8的常见兼容问题
2016/03/13    

x
 
1
<attach event="ondocumentready" handler="easyIeSet">
2
<script language="JScript">
3
    //使用方法将代码保存为easyIe.htc;在样式表中加入样式最好用绝对路径:body{behavior:url(/styles/easyIe.htc);};
4
    //1.ie6或7不缓存背景图片;
5
    //2.ie6,7,8不支持半透明效果;改后导致该dom出现overflow:hidden,特殊情况ie7下不支持半透明,用1像素半透明png平铺或直接pass掉;
6
    //3.ie6不支持hover效果;每个dom元素,当mouseenter的时候加上这个dom的名字(小写)和onhover的组合(例如:div鼠标放上后会追加样式divonhover,一开后会移除divonhover;样式表这么写div:hover,divonhover{font-weight:bold;}),速度比hover.htc要快几倍哦!
7
    //4.ie6支持fixed;
8
    //5.ie6支持PNG半透明效果;
9
    //6.圆角线,性渐变,boxshadow需要引入PIE.htc,并在PIE所在文件夹里放入PIE_IE678js和PIE_9.js,查找behavior: url(/styles/PIE.htc),路径为绝对路径;线性渐变需要在cssText里加入-pie-background: linear-gradient(#EEFF99, #66EE33);
10
    //authour:刘丕水,zhuifengh2o
11
    var currentSheet, doc = window.document;
12
    var userAgentNow = navigator.userAgent.toString();
13
    var ie6Rgx = new RegExp("MSIE 6.0");
14
    var ie7Rgx = new RegExp("MSIE 7.0");
15
    var ie8Rgx = new RegExp("MSIE 8.0");
16
    var ie9Rgx = new RegExp("MSIE 9.0");
17
    var isIE6 = ie6Rgx.test(userAgentNow);
18
    var isIE7 = ie7Rgx.test(userAgentNow);
19
    var isIE8 = ie8Rgx.test(userAgentNow);
20
    var isIE9 = ie9Rgx.test(userAgentNow);
21
    //html5元素支持开始
22
    //需要在html页面的head里加上JS地址为http://html5shiv.googlecode.com/svn/trunk/html5.js相关文章http://www.cnblogs.com/jhti/archive/2011/07/13/2105039.html;增加canvas支持需要引入excanvas.compiled.js,相关文章http://blog.csdn.net/huang100qi/article/details/7698647(让IE8支持canvas功能);
23
    //html5支持结束
24
window['DD_belatedPNG'] = {
25
        ns: 'DD_belatedPNG',
26
        imgSize: {},
27
        delay: 10,
28
        nodesFixed: 0,
29
        createVmlNameSpace: function () {
30
                if (document.namespaces && !document.namespaces[blog_post.ns]) {
31
                        document.namespaces.add(blog_post.ns, 'urn:schemas-microsoft-com:vml');
32
                }
33
        },
34
        createVmlStyleSheet: function () {
35
                var screenStyleSheet, printStyleSheet;
36
                screenStyleSheet =$("<style media='screen'></style>");
37
                $("head").append(screenStyleSheet);
38
                if (screenStyleSheet[0].styleSheet) {
39
                        screenStyleSheet = screenStyleSheet[0].styleSheet;
40
                        screenStyleSheet.addRule(blog_post.ns + '\:*', '{behavior:url(#default#VML)}');
41
                        screenStyleSheet.addRule(blog_post.ns + '\:shape', 'position:absolute;');
42
                        screenStyleSheet.addRule('img.' + blog_post.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/ */
43
                        blog_post.screenStyleSheet = screenStyleSheet;
44
                        printStyleSheet = $("<style media='print'></style>");
45
                        $("head").prepend(printStyleSheet);
46
                        printStyleSheet = printStyleSheet[0].styleSheet;
47
                        printStyleSheet.addRule(blog_post.ns + '\:*', '{display: none !important;}');
48
                        printStyleSheet.addRule('img.' + blog_post.ns + '_sizeFinder', '{display: none !important;}');
49
                }
50
        },
51
        readPropertyChange: function () {
52
                var el, display, v;
53
                el = event.srcElement;
54
                if (!el.vmlInitiated) {
55
                        return;
56
                }
57
                if (~event.propertyName.search('background') || (~event.propertyName.search('border'))) {
58
                        DD_belatedPNG.applyVML(el);
59
                }
60
                if (event.propertyName == 'style.display') {
61
                        display = (el.currentStyle.display == 'none') ? 'none' : 'block';
62
                        for (v in el.vml) {
63
                                if (el.vml.hasOwnProperty(v)) {
64
                                        el.vml[v].shape.style.display = display;
65
                                }
66
                        }
67
                }
68
                if (~event.propertyName.search('filter')) {
69
                        DD_belatedPNG.vmlOpacity(el);
70
                }
71
        },
72
        vmlOpacity: function (el) {
73
                if (~el.currentStyle.filter.search('lpha')) {
74
                        var trans = el.currentStyle.filter;
75
                        trans = parseInt(trans.substring(trans.lastIndexOf('=')+1, trans.lastIndexOf(')')), 10)/100;
76
                        el.vml.color.shape.style.filter = el.currentStyle.filter; /* complete guesswork */
77
                        el.vml.image.fill.opacity = trans; /* complete guesswork */
78
                }
79
        },
80
        handlePseudoHover: function (el) {
81
                setTimeout(function () { /* wouldn't work as intended without setTimeout */
82
                        DD_belatedPNG.applyVML(el);
83
                }, 1);
84
        },
85
        applyVML: function (el) {
86
                el.runtimeStyle.cssText = '';
87
                blog_post.vmlFill(el);
88
                blog_post.vmlOffsets(el);
89
                blog_post.vmlOpacity(el);
90
                if (el.isImg) {
91
                        blog_post.copyImageBorders(el);
92
                }
93
        },
94
        attachHandlers: function (el) {
95
                var self, handlers, handler, moreForAs, a, h;
96
                self = blog_post;
97
                handlers = {resize: 'vmlOffsets', move: 'vmlOffsets'};
98
                if (el.nodeName == 'A') {
99
                        moreForAs = {mouseleave: 'handlePseudoHover', mouseenter: 'handlePseudoHover', focus: 'handlePseudoHover', blur: 'handlePseudoHover'};
100
                        for (a in moreForAs) {                        
101
                                if (moreForAs.hasOwnProperty(a)) {
102
                                        handlers[a] = moreForAs[a];
103
                                }
104
                        }
105
                }
106
                for (h in handlers) {
107
                        if (handlers.hasOwnProperty(h)) {
108
                                handler = function () {
109
                                        self[handlers[h]](el);
110
                                };
111
                                el.attachEvent('on' + h, handler);
112
                        }
113
                }
114
                el.attachEvent('onpropertychange', blog_post.readPropertyChange);
115
        },
116
        giveLayout: function (el) {
117
                el.style.zoom = 1;
118
                 if (el.currentStyle.position == 'static') {
119
                            el.style.position = 'relative'
120
                }
121
            },
122
        copyImageBorders: function (el) {
123
                var styles, s;
124
                styles = {'borderStyle':true, 'borderWidth':true, 'borderColor':true};
125
                for (s in styles) {
126
                        if (styles.hasOwnProperty(s)) {
127
                                el.vml.color.shape.style[s] = el.currentStyle[s];
128
                        }
129
                }
130
        },
131
        vmlFill: function (el) {
132
                if (!el.currentStyle) {
133
                        return;
134
                } else {
135
                        var elStyle, noImg, lib, v, img, imgLoaded;
136
                        elStyle = el.currentStyle;
137
                }
138
                for (v in el.vml) {
139
                        if (el.vml.hasOwnProperty(v)) {
140
                                el.vml[v].shape.style.zIndex = elStyle.zIndex;
141
                        }
142
                }
143
                el.runtimeStyle.backgroundColor = '';
144
                el.runtimeStyle.backgroundImage = '';
145
                noImg = true;
146
                if (elStyle.backgroundImage != 'none' || el.isImg) {
147
                        if (!el.isImg) {
148
                                el.vmlBg = elStyle.backgroundImage;
149
                                el.vmlBg = el.vmlBg.substr(5, el.vmlBg.lastIndexOf('")')-5);
150
                        }
151
                        else {
152
                                el.vmlBg = el.src;
153
                        }
154
                        lib = blog_post;
155
                        if (!lib.imgSize[el.vmlBg]) { /* determine size of loaded image */
156
                                img = document.createElement('img');
157
                                lib.imgSize[el.vmlBg] = img;
158
                                img.className = lib.ns + '_sizeFinder';
159
                                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! */
160
                                imgLoaded = function () {
161
                                        blog_post.width = blog_post.offsetWidth; /* weird cache-busting requirement! */
162
                                        blog_post.height = blog_post.offsetHeight;
163
                                        lib.vmlOffsets(el);
164
                                };
165
                                img.attachEvent('onload', imgLoaded);
166
                                img.src = el.vmlBg;
167
                                img.removeAttribute('width');
168
                                img.removeAttribute('height');
169
                                $("body").prepend($(img));
170
                        }
171
                        el.vml.image.fill.src = el.vmlBg;
172
                        noImg = false;
173
                }
174
                el.vml.image.fill.on = !noImg;
175
                el.vml.image.fill.color = 'none';
176
                el.vml.color.shape.style.backgroundColor = elStyle.backgroundColor;
177
                el.runtimeStyle.backgroundImage = 'none';
178
                el.runtimeStyle.backgroundColor = 'transparent';
179
        },
180
        vmlOffsets: function (el) {
181
                var blog_postStyle, size, fudge, makeVisible, bg, bgR, dC, altC, b, c, v;
182
                blog_postStyle = el.currentStyle;
183
                size = {'W':el.clientWidth+1, 'H':el.clientHeight+1, 'w':blog_post.imgSize[el.vmlBg].width, 'h':blog_post.imgSize[el.vmlBg].height, 'L':el.offsetLeft, 'T':el.offsetTop, 'bLW':el.clientLeft, 'bTW':el.clientTop};
184
                fudge = (size.L + size.bLW == 1) ? 1 : 0;
185
                makeVisible = function (vml, l, t, w, h, o) {
186
                        vml.coordsize = w+','+h;
187
                        vml.coordorigin = o+','+o;
188
                        vml.path = 'm0,0l'+w+',0l'+w+','+h+'l0,'+h+' xe';
189
                        vml.style.width = w + 'px';
190
                        vml.style.height = h + 'px';
191
                        vml.style.left = l + 'px';
192
                        vml.style.top = t + 'px';
193
                };
194
                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);
195
                makeVisible(el.vml.image.shape, (size.L + size.bLW), (size.T + size.bTW), (size.W), (size.H), 1 );
196
                bg = {'X':0, 'Y':0};
197
                if (el.isImg) {
198
                        bg.X = parseInt(blog_postStyle.paddingLeft, 10) + 1;
199
                        bg.Y = parseInt(blog_postStyle.paddingTop, 10) + 1;
200
                }
201
                else {
202
                        for (b in bg) {
203
                                if (bg.hasOwnProperty(b)) {
204
                                        blog_post.figurePercentage(bg, size, b, blog_postStyle['backgroundPosition'+b]);
205
                                }
206
                        }
207
                }
208
                el.vml.image.fill.position = (bg.X/size.W) + ',' + (bg.Y/size.H);
209
                bgR = blog_postStyle.backgroundRepeat;
210
                dC = {'T':1, 'R':size.W+fudge, 'B':size.H, 'L':1+fudge}; 
211
                altC = { 'X': {'b1': 'L', 'b2': 'R', 'd': 'W'}, 'Y': {'b1': 'T', 'b2': 'B', 'd': 'H'} };
212
                if (bgR != 'repeat' || el.isImg) {
213
                        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 */
214
                        if (~bgR.search('repeat-')) { /* now let's revert to dC for repeat-x or repeat-y */
215
                                v = bgR.split('repeat-')[1].toUpperCase();
216
                                c[altC[v].b1] = 1;
217
                                c[altC[v].b2] = size[altC[v].d];
218
                        }
219
                        if (c.B > size.H) {
220
                                c.B = size.H;
221
                        }
222
                        el.vml.image.shape.style.clip = 'rect('+c.T+'px '+(c.R+fudge)+'px '+c.B+'px '+(c.L+fudge)+'px)';
223
                }
224
                else {
225
                        el.vml.image.shape.style.clip = 'rect('+dC.T+'px '+dC.R+'px '+dC.B+'px '+dC.L+'px)';
226
                }
227
        },
228
        figurePercentage: function (bg, size, axis, position) {
229
                var horizontal, fraction;
230
                fraction = true;
231
                horizontal = (axis == 'X');
232
                switch(position) {
233
                        case 'left':
234
                        case 'top':
235
                                bg[axis] = 0;
236
                                break;
237
                        case 'center':
238
                                bg[axis] = 0.5;
239
                                break;
240
                        case 'right':
241
                        case 'bottom':
242
                                bg[axis] = 1;
243
                                break;
244
                        default:
245
                                if (position.search('%') != -1) {
246
                                        bg[axis] = parseInt(position, 10) / 100;
247
                                }
248
                                else {
249
                                        fraction = false;
250
                                }
251
                }
252
                bg[axis] = Math.ceil(  fraction ? ( (size[horizontal?'W': 'H'] * bg[axis]) - (size[horizontal?'w': 'h'] * bg[axis]) ) : parseInt(position, 10)  );
253
                if (bg[axis] % 2 === 0) {
254
                        bg[axis]++;
255
                }
256
                return bg[axis];
257
        },
258
        fixPng: function (el) {
259
                el.style.behavior = 'none';
260
                var lib, els, nodeStr, v, e;
261
                if (el.nodeName == 'BODY' || el.nodeName == 'TD' || el.nodeName == 'TR') { /* elements not supported yet */
262
                        return;
263
                }
264
                el.isImg = false;
265
                if (el.nodeName == 'IMG') {
266
                        if(/.png(?:W|$)/.test(el.src.toLowerCase())) {
267
                                el.isImg = true;
268
                                el.style.visibility = 'hidden';
269
                        }
270
                        else {
271
                                return;
272
                        }
273
                }
274
                else if (el.currentStyle.backgroundImage.toLowerCase().search('.png') == -1) {
275
                        return;
276
                }
277
                lib = DD_belatedPNG;
278
                el.vml = {color: {}, image: {}};
279
                els = {shape: {}, fill: {}};
280
                for (v in el.vml) {
281
                        if (el.vml.hasOwnProperty(v)) {
282
                                for (e in els) {
283
                                        if (els.hasOwnProperty(e)) {
284
                                                nodeStr = lib.ns + ':' + e;
285
                                                el.vml[v][e] = document.createElement(nodeStr);
286
                                        }
287
                                }
288
                                el.vml[v].shape.stroked = false;
289
                                el.vml[v].shape.appendChild(el.vml[v].fill);
290
                                el.parentNode.insertBefore(el.vml[v].shape, el);
291
                        }
292
                }
293
                el.vml.image.shape.fillcolor = 'none'; /* Don't show blank white shapeangle when waiting for image to load. */
294
                el.vml.image.fill.type = 'tile'; /* Makes image show up. */
295
                el.vml.color.fill.on = false; /* Actually going to apply vml element's style.backgroundColor, so hide the whiteness. */
296
                lib.attachHandlers(el);
297
                lib.giveLayout(el);
298
                lib.giveLayout(el.offsetParent);
299
                el.vmlInitiated = true;
300
                lib.applyVML(el); /* Render! */
301
        },
302
        /**
303
        * This is the method to use in a document.
304
        * @param {String} selector - REQUIRED - a CSS selector, such as '#doc .container'
305
        **/
306
        fix: function (selectors) {
307
                if (blog_post.screenStyleSheet) {
308
                        for (var i in selectors) {
309
                                blog_post.screenStyleSheet.addRule(selectors[i], 'behavior:expression(DD_belatedPNG.fixPng(blog_post))'); /* seems to execute the function without adding it to the stylesheet - interesting... */
310
                        }
311
                }
312
        }
313
};
314
function easyIeLoadScript(url, callback){
315
    var script = document.createElement ("script")
316
    script.type = "text/javascript";
317
        script.onreadystatechange = function(){
318
            if (script.readyState == "loaded" || script.readyState == "complete"){
319
                script.onreadystatechange = null;
320
                callback();
321
            }
322
        };
323
    script.src = url;
324
    document.getElementsByTagName("head")[0].appendChild(script);
325
}
326
327
window['easyIeReset']=function(){
328
    if(isIE6){
329
        try{
330
        DD_belatedPNG.createVmlNameSpace();
331
        DD_belatedPNG.createVmlStyleSheet();
332
        } catch (e){};
333
    }
334
        var objReset=new Object();
335
        objReset.pngFixed=new Array();
336
        objReset.Fixed=new Array();
337
    var easyIeBgImgCache=function(){//设置背景缓存 ie6和ie7需要设置
338
        try{document.execCommand('BackgroundImageCache', false, true);} catch (e){};
339
    }
340
341
    var easyIeFixedBg=function(){//fixed的时候需要设置body背景
342
                if($('body').css('background-image')=='none'){$('body').css('background-image','url(about:blank)');}
343
                if($('html').css('background-image')=='none'){$('html').css('background-image','url(about:blank)');}
344
                $("head").append("<style type='text/css'>html,body{background-attachment:fixed;overflow-x:hidden;}</style>")
345
        }
346
    var easyIehover=function(){//ie6不支持hover
347
        $("html").delegate('*', 'mouseenter', function () {if($(blog_post)[0].tagName.toLowerCase=='a'){return;};$(blog_post).addClass($(blog_post)[0].tagName.toLowerCase()+'onhover');});
348
        $("html").delegate('*', 'mouseleave', function () {if($(blog_post)[0].tagName.toLowerCase=='a'){return;};$(blog_post).removeClass($(blog_post)[0].tagName.toLowerCase()+'onhover');});
349
    }
350
351
        parseStylesheets();
352
            if (isIE6) {
353
                    easyIeBgImgCache();
354
                    easyIehover();
355
                    easyIeFixedBg();
356
                    objReset.pngFixed.push("img");
357
                    DD_belatedPNG.fix(objReset.pngFixed);
358
            }
359
        if (isIE7) {
360
                easyIeBgImgCache();
361
            };
362
            function parseStylesheets() {
363
364
                var sheets = doc.styleSheets, l = sheets.length;
365
                for (var i = 0; i < l; i++) {
366
                    parseStylesheet(sheets[i]);
367
                };
368
            };
369
            function parseStylesheet(sheet) {
370
            /***imports不考虑imports导入样式现在都为link引入;如果有导入样式,建议改为link引入
371
                if (sheet.imports) {
372
                    try {
373
                        var imports = sheet.imports, l = imports.length;
374
                        for (var i = 0; i < l; i++) {
375
                            parseStylesheet(sheet.imports[i]);
376
                        };
377
                    } catch (securityException) { };
378
                };***/
379
                try {
380
                    var rules = (currentSheet = sheet).rules, rulesl = rules.length;
381
                    for (var j = 0; j < rulesl; j++) {
382
383
                        parseCSSRule(rules[j]);
384
                    };
385
                } catch (securityException) { };
386
            };
387
            function parseCSSRule(rule) {
388
                var select = rule.selectorText, style = rule.style.cssText.toLowerCase();
389
                if (!isIE9) {
390
                    var t = style.match(/opacity:(|s*)0.(d+)/);
391
                    var newSelectAlpha = select;
392
                    if ((typeof (t) != "undefined") & (t != 0) & (t != null)) {
393
                        var styleOpacity = "filter:alpha(opacity=" + t[2] * 10 + ");";
394
                        currentSheet.addRule(newSelectAlpha, styleOpacity);
395
                    };
396
                }
397
398
                    if (~style.indexOf('border-radius') ||(~style.indexOf('linear-gradient')) || (~style.indexOf('box-shadow'))) {//添加使IE支持圆角,渐变,阴影;
399
            var styleRadius = "behavior: url(/styles/PIE.htc)";
400
                        currentSheet.addRule(select, styleRadius);
401
                    }
402
                    if (isIE6) {
403
                        if ((/png/).test(style)) {
404
                        objReset.pngFixed.push(select);
405
                        }
406
                    }
407
                    if (isIE6) {
408
                        if ((/position:sfixed/).test(style)) {
409
                            if (!((/absolute/).test(style))) {
410
                                styleAbsoute = "position:absolute";
411
                                currentSheet.addRule(select, styleAbsoute);
412
                            }
413
                            if ((/bottom/).test(style)) {
414
                                var bottomNum = (style).match(/(bottom:s)+(d+)/i)[2];
415
                                var fixedStylenow = "top:expression(eval(document.documentElement.scrollTop+document.documentElement.clientHeight-blog_post.offsetHeight-(parseInt(blog_post.currentStyle.marginTop,10)||0)-(parseInt(blog_post.currentStyle.marginBottom,10)||0)-" + bottomNum + "));"
416
                                currentSheet.addRule(select, fixedStylenow);
417
                            } else {
418
                                if ((/top/).test(style)) {
419
                                    var topNum = (style).match(/(top:s)+(d+)/i)[2];
420
                                    var fixedStylenow = "top:expression(eval(document.documentElement.scrollTop+" + topNum + "));"
421
                                    currentSheet.addRule(select, fixedStylenow);
422
                                } else {
423
                                    var topNum = 0;
424
                                    var fixedStylenow = "top:expression(eval(document.documentElement.scrollTop+" + topNum + "));"
425
                                    currentSheet.addRule(select, fixedStylenow);
426
                                }
427
                            }
428
                        };
429
430
431
                    }
432
            };
433
    }
434
   var easyIeSet=easyIeLoadScript('http://cdn.staticfile.org/jquery/1.7.2/jquery.min.js',easyIeReset);
435
</script>