简体   繁体   English

在没有库的情况下在JavaScript中检查IE小于9的最佳方法

[英]Best way to check for IE less than 9 in JavaScript without library

在没有使用jQuery或任何附加库的情况下,在JavaScript中检测浏览器IE和版本低于9的最快,最短(最佳)方法是什么?

Javascript 使用Javascript

var ie = (function(){

    var undef,
        v = 3,
        div = document.createElement('div'),
        all = div.getElementsByTagName('i');

    while (
        div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
        all[0]
    );

    return v > 4 ? v : undef;

}());

You can then do: 然后你可以这样做:

ie < 9

By James Panolsey from here: http://james.padolsey.com/javascript/detect-ie-in-js-using-conditional-comments 来自这里的James Panolsey: http ://james.padolsey.com/javascript/detect-ie-in-js-using-conditional-comments

for what it's worth: 物有所值:

    if(  document.addEventListener  ){
        alert("you got IE9 or greater");
    }

This successfully targets IE 9+ because the addEventListener method was supported very early on for every major browser but IE. 这成功地针对IE 9+,因为addEventListener方法很早就支持每个主要的浏览器,但IE。 (Chrome, Firefox, Opera, and Safari) MDN Reference . (Chrome,Firefox,Opera和Safari) MDN参考 It is supported currently in IE9 and we can expect it to continue to be supported here on out. 它目前在IE9中得到支持,我们可以预期它将继续得到支持。

Using conditional comments, you can create a script block that will only get executed in IE less than 9. 使用条件注释,您可以创建一个仅在小于9的IE中执行的脚本块。

<!--[if lt IE 9 ]>
<script>
var is_ie_lt9 = true;
</script>
<![endif]--> 

Of course, you could precede this block with a universal block that declares var is_ie_lt9=false , which this would override for IE less than 9. (In that case, you'd want to remove the var declaration, as it would be repetitive). 当然,你可以在这个块之前加上一个声明var is_ie_lt9=false的通用块,这将覆盖IE小于9的值。(在这种情况下,你要删除var声明,因为它会重复) 。

EDIT : Here's a version that doesn't rely on in-line script blocks (can be run from an external file), but doesn't use user agent sniffing: 编辑 :这是一个不依赖于内联脚本块的版本(可以从外部文件运行),但不使用用户代理嗅探:

Via @cowboy : 通过@cowboy

with(document.createElement("b")){id=4;while(innerHTML="<!--[if gt IE "+ ++id+"]>1<![endif]-->",innerHTML>0);var ie=id>5?+id:0}

bah to conditional comments! bah有条件的评论! Conditional code all the way!!! 条件代码一路!!! (silly IE) (愚蠢的IE)

<script type="text/javascript">
/*@cc_on
   var IE_LT_9 = (@_jscript_version < 9);
@*/
</script>

Seriously though, just throwing this out there in case it suits you better... they're the same thing, this can just be in a .js file instead of inline HTML 但是说真的,只要把它扔到那里以防它更适合你...它们是同一个东西,这可以只是在.js文件而不是内联HTML

Note: it is entirely coincidental that the jscript_version check is "9" here. 注意:这里的jscript_version检查为“9”完全是巧合。 Setting it to 8, 7, etc will NOT check "is IE8", you'd need to lookup the jscript versions for those browsers. 将其设置为8,7等不会检查“是IE8”,您需要查找这些浏览器的jscript版本。

Below is an improvement over James Padolsey's solution: 以下是对James Padolsey解决方案的改进:

1) It doesn't pollute memory (James' snippet creates 7 unremoved document fragments when detecting IE11, for example). 1)它不会污染内存(例如,当检测到IE11时,James的代码片段会创建7个未删除的文档片段)。
2) It's faster since it checks for a documentMode value before generating markup. 2)它更快,因为它在生成标记之前检查documentMode值。
3) It's far more legible, especially to beginning JavaScript programmers. 3)它更易读,特别是对于初学JavaScript程序员。

Gist link: https://gist.github.com/julianshapiro/9098609 要点链接: https//gist.github.com/julianshapiro/9098609

/*
 - Behavior: For IE8+, we detect the documentMode value provided by Microsoft.
 - Behavior: For <IE8, we inject conditional comments until we detect a match.
 - Results: In IE, the version is returned. In other browsers, false is returned.
 - Tip: To check for a range of IE versions, use if (!IE || IE < MAX_VERSION)...
*/

var IE = (function() { 
    if (document.documentMode) {
        return document.documentMode;
    } else {
        for (var i = 7; i > 0; i--) {
            var div = document.createElement("div");

            div.innerHTML = "<!--[if IE " + i + "]><span></span><![endif]-->";

            if (div.getElementsByTagName("span").length) {
                return i;
            }
        }
    }

    return undefined;
})();
var ie = !-[1,]; // true if IE less than 9

This hack is supported in ie5,6,7,8. ie5,6,7,8支持这种黑客攻击。 It is fixed in ie9+ (so it suits demands of this question). 它固定在ie9 +(所以它适合这个问题的要求)。 This hack works in all IE compatibility modes. 此hack适用于所有IE兼容模式。

How it works : ie engine treat array with empty element (like this [,1]) as array with two elements, instead other browsers think that there is only one element. 它是如何工作的 :即引擎处理带有空元素的数组(如此[,1])作为带有两个元素的数组,而其他浏览器则认为只有一个元素。 So when we convert this array to number with + operator we do something like that: (',1' in ie / '1' in others)*1 and we get NaN in ie and 1 in others. 因此,当我们使用+运算符将此数组转换为数字时,我们会执行类似的操作:(',1'在ie /'1'在其他情况下)* 1,我们在ie中获得NaN,在其他中获得1。 Than we transform it to boolean and reverse value with !. 然后用!将它转换为布尔值和反向值。 Simple. 简单。 By the way we can use shorter version without ! 顺便说一句,我们可以使用更短的版本! sign, but value will be reversed. 标志,但价值将被逆转。

This is the shortest hack by now. 这是目前最短的黑客攻击。 And I am the author ;) 我是作者;)

I've decided to go with object detection instead. 我决定改用对象检测。

After reading this: http://www.quirksmode.org/js/support.html and this: http://diveintohtml5.ep.io/detect.html#canvas 阅读本文后: http//www.quirksmode.org/js/support.html和此: http//diveintohtml5.ep.io/detect.html#canvas

I'd use something like 我会用类似的东西

if(!!document.createElement('canvas').getContext) alert('what is needed, supported');

This link contains relevant information on detecting versions of Internet Explorer: 此链接包含有关检测Internet Explorer版本的相关信息:

http://tanalin.com/en/articles/ie-version-js/ http://tanalin.com/en/articles/ie-version-js/

Example: 例:

if (document.all && !document.addEventListener) {
    alert('IE8 or older.');
}

You could do it in a quick and dirty fashion with a regular expression and .match() : 你可以使用正则表达式和.match()以快速而肮脏的方式完成它:

if (navigator.userAgent.match(/MSIE\s(?!9.0)/)) {
    // ie less than version 9
}

If I were you I would use conditional compilation or feature detection. 如果我是你,我会使用条件编译或特征检测。
Here's another alternative: 这是另一种选择:

<!--[if lt IE 9]><!-->
<script>
    var LTEIE8 = true;
</script>
<!--<![endif]-->

I liked Mike Lewis' answer but the code did not pass jslint and I could not understand the funky while loop. 我喜欢Mike Lewis的回答,但是代码没有通过jslint,我无法理解那个时髦的循环。 My use case is to put up a browser not supported message if less than or equal to IE8. 我的用例是在IE8小于或等于IE8的情况下建立浏览器不支持的消息。

Here is a jslint free version based on Mike Lewis': 这是一个基于Mike Lewis'的jslint免费版:

/*jslint browser: true */
/*global jQuery */
(function () {
    "use strict";
    var browserNotSupported = (function () {
        var div = document.createElement('DIV');
        // http://msdn.microsoft.com/en-us/library/ms537512(v=vs.85).aspx
        div.innerHTML = '<!--[if lte IE 8]><I></I><![endif]-->';
        return div.getElementsByTagName('I').length > 0;
    }());
    if (browserNotSupported) {
        jQuery("html").addClass("browserNotSupported").data("browserNotSupported", browserNotSupported);
    }
}());

Does it need to be done in JavaScript? 是否需要在JavaScript中完成?

If not then you can use the IE-specific conditional comment syntax: 如果没有,那么您可以使用特定于IE的条件注释语法:

<!--[if lt IE 9]><h1>Using IE 8 or lower</h1><![endif]-->
if (+(/MSIE\s(\d+)/.exec(navigator.userAgent)||0)[1] < 9) {
    // IE8 or less
}
  • extract IE version with: /MSIE\\s(\\d+)/.exec(navigator.userAgent) 提取IE版本:/ /MSIE\\s(\\d+)/.exec(navigator.userAgent) /. /MSIE\\s(\\d+)/.exec(navigator.userAgent)
  • if it's non-IE browser this will return null so in that case ||0 will switch that null to 0 如果它是非IE浏览器,则返回null因此在这种情况下||0将该null切换为0
  • [1] will get major version of IE or undefined if it was not an IE browser 如果它不是IE浏览器, [1]将获得IE的主要版本或undefined
  • leading + will convert it into a number, undefined will be converted to NaN leading +会将其转换为数字, undefined将转换为NaN
  • comparing NaN with a number will always return false NaN与数字进行比较将始终返回false

You are all trying to overcomplicate such simple things. 你们都在努力使这些简单的东西过于复杂。 Just use a plain and simple JScript conditional comment. 只需使用简单明了的JScript条件注释即可。 It is the fastest because it adds zero code to non-IE browsers for the detection, and it has compatibility dating back to versions of IE before HTML conditional comments were supported. 它是最快的,因为它为非IE浏览器添加零代码以进行检测,并且在支持HTML条件注释之前,它具有可追溯到IE版本的兼容性。 In short, 简而言之,

var IE_version=(-1/*@cc_on,@_jscript_version@*/);

Beware of minifiers: most (if not all) will mistake the special conditional comment for a regular comment, and remove it 注意缩小器:大多数(如果不是全部)会将特殊条件注释误认为是常规注释,并将其删除

Basically, then above code sets the value of IE_version to the version of IE you are using, or -1 f you are not using IE. 基本上,然后上面的代码将IE_version的值设置为您正在使用的IE版本,或者-1如果您没有使用IE。 A live demonstration: 现场演示:

 var IE_version=(-1/*@cc_on,@_jscript_version@*/); if (IE_version!==-1){ document.write("<h1>You are using Internet Explorer " + IE_version + "</h1>"); } else { document.write("<h1>You are not using a version of Internet Explorer less than 11</h1>"); } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM