如何使用条件编译来嗅IE8

时间:2011-07-09 13:21:01

标签: javascript internet-explorer-8 internet-explorer-7 conditional-compilation

我想嗅掉当前版本的IE8(我很抱歉,但没有别的办法,我必须这样做)。我知道应该使用功能嗅探而不是浏览器嗅探,但是,嘿,我的老板不知道,对吧?

现在我使用了这个条件编译代码:

var ie8 = false/*@cc_on @_jscript_version == 8@*/

但似乎它还包括IE7。有什么想法吗?

3 个答案:

答案 0 :(得分:3)

如果不使用条件编译,您可以使用条件注释在html元素上为要测试的每个IE设置一个类,例如:

<!--[if lt IE 7 ]> <html lang="en" class="ie6"> <![endif]-->
<!--[if IE 7 ]>    <html lang="en" class="ie7"> <![endif]-->
<!--[if IE 8 ]>    <html lang="en" class="ie8"> <![endif]-->
<!--[if IE 9 ]>    <html lang="en" class="ie9"> <![endif]-->
<!--[if (gt IE 9)|!(IE)]><!--> <html lang="en"> <!--<![endif]-->

(来自http://initializr.com/

然后在JS中测试类是一个简单的问题:

var ie8 = !!document.getElementsByTagName("html")[0].className.match(/ie8/);

答案 1 :(得分:3)

以下假设您使用的是Internet Explorer ...

首先,测试浏览器版本是异常 - document.documentMode应该进行测试(因为即使使用IE9或IE10,页面也可以处于IE8模式):

if (document.documentMode == 8) { ...

如果您有一些真正的奇怪的要求,那么您可以可靠地检测JScript版本,例如IE8的_jscript_version是5.8(见http://en.wikipedia.org/wiki/Conditional_comment):

var ieJsVer = Function('return/*@cc_on @_jscript_version @*/;')();
var isIE8 = (ieJsVer == 5.8);

条件注释放在一个字符串中,这样就不会被任何可能发生的JavaScript压缩删除(这可能会删除注释)。

重要 Internet Explorer 11 编辑:

  • 补充说;在Function()字符串的末尾 - 否则在EDGE模式下IE11会抛出异常 - arrrgh!
  • IE11处于EDGE模式,然后ieJsVer未定义
  • IE11在docMode&lt; = 10然后ieJsVer是11
  • EDGE模式下的IE11为document.documentMode
  • 返回undefined

答案 2 :(得分:1)

为什么不使用条件注释来切换设置变量的脚本?像:

<head>
    <script>
        window.ie8 = false;
    </script>
    <!--[if IE 8]>
        <script>
            window.ie8 = true;
        </script>
    <![endif]-->
</head>

虽然它有点冗长,但也许它更可靠。