码迷,mamicode.com
首页 > Web开发 > 详细

条件注释+JS实现各版本IE浏览器className

时间:2015-05-13 19:09:33      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:

最近又开始忙了,项目中又遇到了可恶的IE Hack问题,各种Hack的看着让自己都觉得恶心,于是决定改造一番。

首先请出条件注释语句:

之前用过的条件注释

<!--[if lt IE 7]><body class="ie6"><![endif]-->
<!--[if IE 7]><body class="ie7"><![endif]-->
<!--[if IE 8]><body class="ie8"><![endif]-->
<!--[if IE 9]><body class="ie9"><![endif]-->
<!--[if !IE]><!--><body><!--<![endif]-->

 

但是这种用法的问题想必大家也都知道,就是:class里只会出现与浏览器模式(Browser Mode)对应的那个类名,不会出现你所期望的文档模式(Document Mode)对应的类名,如下面截图(在IE9浏览器中,设置页面以IE8文档模式呈现):

技术分享

 

解决方法 

 使用改进的条件注释语句:

<!--[if lt IE 7]><body class="ie6 ielt7 ielt8 ielt9 ielt10 ie"><![endif]-->
<!--[if IE 7]><body class="ie7 ielt8 ielt9 ielt10 ie"><![endif]-->
<!--[if IE 8]><body class="ie8 ie"><![endif]-->
<!--[if IE 9]><body class="ie9 ie"><![endif]-->
<!--[if (gt IE 9)|!(IE)]><!--><body><!--<![endif]-->


配合JS代码(否则还是没用滴~~):

var isIE = !!window.ActiveXObject;
var isIE6 = isIE && !window.XMLHttpRequest;
var gtIE8 = isIE && !!document.documentMode;
var isIE7 = isIE && !isIE6 && !gtIE8 || (document.documentMode==7);
//Reset body class for IE8+ CSS hack
if(gtIE8){
    window.onload = function(){
        if( document.getElementsByTagName("body")[0] ){
            if( !document.documentMode ) return;
            var classStr = document.getElementsByTagName("body")[0].className;
            classStr = classStr.replace(/\sielt\d+/g, "");
            classStr = classStr.replace(/ie\d+/g, "ie" + document.documentMode);
            for(var i = document.documentMode+1, j = 10; i <= j; i++ ){
                classStr += (" ielt"+i);    
            }
            document.getElementsByTagName("body")[0].className = classStr;
        }
    }
}


其实就是用正则来替换一下,成功达到目的(只让文档模式~~):

技术分享

技术分享

技术分享

技术分享

条件注释+JS实现各版本IE浏览器className

标签:

原文地址:http://www.cnblogs.com/divayang/p/4500921.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!