[英]How to use conditional compile to sniff IE8
I want to sniff the current version of IE8 (and I'm so sorry, but no other way, I have to do that).我想嗅探当前版本的 IE8(我很抱歉,但别无他法,我必须这样做)。 I know that feature sniffing should be used instead of browser sniffing, but hey, my boss doesn't know that, right?
我知道应该使用特征嗅探而不是浏览器嗅探,但是,嘿,我的老板不知道,对吧?
Now I used this conditional compiling code:现在我使用了这个条件编译代码:
var ie8 = false/*@cc_on @_jscript_version == 8@*/
But seems that it also includes IE7.但似乎它也包括IE7。 Any idea?
任何想法?
Without using conditional compiles, you could use conditional comments to set a class on the html
element for each IE you want to test for, like:在不使用条件编译的情况下,您可以使用条件注释在
html
元素上为要测试的每个 IE 设置 class,例如:
<!--[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]-->
(from http://initializr.com/ ) (来自http://initializr.com/ )
Then it would be a simple matter of testing for the class in JS:那么在JS中测试class就很简单了:
var ie8 = !!document.getElementsByTagName("html")[0].className.match(/ie8/);
The following presumes you are using Internet Explorer...以下假设您使用的是 Internet Explorer...
Firstly, it is extremely abnormal to test for the browser version - the document.documentMode is what should be tested for (because a page can be in IE8 mode even if using IE9 or IE10):首先,测试浏览器版本是非常不正常的——应该测试document.documentMode(因为一个页面即使使用IE9或IE10也可以是IE8模式):
if (document.documentMode == 8) { ...
If you have some really strange requirement, then you can reliably detect the JScript version eg _jscript_version is 5.8 for IE8 (see http://en.wikipedia.org/wiki/Conditional_comment ):如果您有一些非常奇怪的要求,那么您可以可靠地检测 JScript 版本,例如 _jscript_version 是 IE8 的 5.8(请参阅http://en.wikipedia.org/wiki/Conditional_comment ):
var ieJsVer = Function('return/*@cc_on @_jscript_version @*/;')();
var isIE8 = (ieJsVer == 5.8);
The conditional comment is put inside a string so that it won't be removed by any JavaScript compression that might occur (which may strip out comments).条件注释被放在一个字符串中,这样它就不会被任何可能发生的 JavaScript 压缩删除(这可能会删除注释)。
Important Internet Explorer 11 edit:重要的Internet Explorer 11编辑:
Why not use conditional comments to toggle a script that sets the variable?为什么不使用条件注释来切换设置变量的脚本? Like:
喜欢:
<head>
<script>
window.ie8 = false;
</script>
<!--[if IE 8]>
<script>
window.ie8 = true;
</script>
<![endif]-->
</head>
Granted it's a bit verbose, but perhaps it's also more reliable.当然它有点冗长,但也许它也更可靠。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.