ChatGPT解决这个技术问题 Extra ChatGPT

在 JavaScript 中检测 IE 版本(v9 之前)

如果我们网站的用户使用的是 v9 之前的 Internet Explorer 版本,我想将他们退回到错误页面。只是不值得我们花时间和金钱来支持 IE pre-v9。所有其他非 IE 浏览器的用户都很好,不应被退回。这是建议的代码:

if(navigator.appName.indexOf("Internet Explorer")!=-1){     //yeah, he's using IE
    var badBrowser=(
        navigator.appVersion.indexOf("MSIE 9")==-1 &&   //v9 is ok
        navigator.appVersion.indexOf("MSIE 1")==-1  //v10, 11, 12, etc. is fine too
    );

    if(badBrowser){
        // navigate to error page
    }
}

这段代码能解决问题吗?

阻止一些可能会出现的评论:

是的,我知道用户可以伪造他们的用户代理字符串。我不担心。是的,我知道编程专业人员更喜欢嗅探功能支持而不是浏览器类型,但我认为这种方法在这种情况下没有意义。我已经知道所有(相关的)非 IE 浏览器都支持我需要的功能,而所有 v9 之前的 IE 浏览器都不支持。在整个站点中逐个检查功能将是一种浪费。是的,我知道有人尝试使用 IE v1(或 >= 20)访问该站点时不会将“badBrowser”设置为 true,并且警告页面也不会正确显示。这是我们愿意承担的风险。是的,我知道微软有“条件注释”,可用于精确的浏览器版本检测。从 IE 10 开始,IE 不再支持条件注释,这使得这种方法完全没用。

还有其他明显的问题需要注意吗?

“支持 IE pre-v9 不值得我们花时间和金钱”。我希望我能做到。
基于第 [2] 点,我不建议使用 Modernizr (en.wikipedia.org/wiki/Modernizr) - 每个人都必须在某处画一条线 - 但 IE9 确实看起来像一条高线
条件注释只是普通注释。只有 IE 将它们解释为特殊的。 IE10+ 不会再这样做了。
IE 10 对条件注释的处理方式与非 IE 浏览器完全相同。它们是有效的 HTML 注释,因此将被视为有效。我同意 Andreas 的观点,并认为有条件的评论是要走的路。
说 IE10+ 不支持条件注释的官方文档:blogs.msdn.com/b/ie/archive/2011/07/06/… - 感谢:stackoverflow.com/a/9900331/320399

C
Chris Halcrow

这是我的首选方式。它提供了最大的控制。 (注意:条件语句仅在 IE5 - 9 中支持。)

首先正确设置你的ie类

<!DOCTYPE html>
<!--[if lt IE 7]> <html class="lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>    <html class="lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>    <html class="lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html> <!--<![endif]-->    
<head>

然后你可以只使用 CSS 来制作样式异常,或者,如果你需要,你可以添加一些简单的 JavaScript:

(function ($) {
    "use strict";

    // Detecting IE
    var oldIE;
    if ($('html').is('.lt-ie7, .lt-ie8, .lt-ie9')) {
        oldIE = true;
    }

    if (oldIE) {
        // Here's your JS for IE..
    } else {
        // ..And here's the full-fat code for everyone else
    }

}(jQuery));

感谢Paul Irish


鉴于 OP 要求提供纯 JavaScript 解决方案,我相信下面@Tim Down 的答案更好,因为它不涉及更改现有 HTML,而且它不使用 jQuery:stackoverflow.com/a/10965203/134120
我在 w3 html 验证器上收到一个错误:Error: Saw <!-- within a comment. Probable cause: Nested comment (not allowed). At line 5, column 21 if gt IE 8]><!--><html
D
DBS

返回 IE 版本或者如果不是 IE 返回 false

function isIE () {
  var myNav = navigator.userAgent.toLowerCase();
  return (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false;
}

例子:

if (isIE () == 8) {
 // IE8 code
} else {
 // Other versions IE or not IE
}

或者

if (isIE () && isIE () < 9) {
 // is IE version less than 9
} else {
 // is IE 9 and later or not IE
}

或者

if (isIE()) {
 // is IE
} else {
 // Other browser
}

不适用于 IE11。从 IE 11 开始,他们已将 UA 字符串更改为 "mozilla/5.0 (windows nt 6.3; wow64; trident/7.0; .net4.0e; .net4.0c; media center pc 6.0; .net clr 3.5.30729; .net clr 2.0.50727; .net clr 3.0.30729; rv:11.0) like gecko"
请注意,在 FF 中,“false < 9”为“true”。所以,条件应该是if (isIE () && isIE () < 9) {
@DeadlyChambers 也许它在 IE7 标准模式下运行? msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
批准的答案是如何检测 HTML 中的 IE 版本。这回答了最初的问题。
@PrasadGayan - Microsoft Edge 不是 Internet Explorer。所以返回 false 似乎是正确的做法。
T
Tim Down

使用条件注释。您正在尝试检测 IE < 9 的用户,并且条件注释将在这些浏览器中运行;在其他浏览器(IE >= 10 和非 IE)中,注释将被视为普通的 HTML 注释,它们就是这样。

示例 HTML:

<!--[if lt IE 9]>
WE DON'T LIKE YOUR BROWSER
<![endif]-->

如果需要,您也可以纯粹使用脚本执行此操作:

var div = document.createElement("div");
div.innerHTML = "<!--[if lt IE 9]><i></i><![endif]-->";
var isIeLessThan9 = (div.getElementsByTagName("i").length == 1);
if (isIeLessThan9) {
    alert("WE DON'T LIKE YOUR BROWSER");
}

@Tim Down 答案的 JavaScript 版本对我来说非常有用。我使用 BrowserStack 在 Windows 7 和 IE 8、9、10 和 11 上对其进行了测试;带有 Safari 5.1、Firefox 28.0、Chrome 33.0 和 Opera 20.0 的 Mac OS X Snow Leopard; iPhone 5 移动版 Safari;和安卓三星 Galaxy Tab 2 10.1 4.0。不出所料,只有 IE8 报告它是 IeLessThan9。好的!
C
Community

如果没有其他人添加了 addEventLister 方法并且您使用的是正确的浏览器模式,那么您可以检查 IE 8 或更低版本

if (window.attachEvent && !window.addEventListener) {
    // "bad" IE
}

Legacy Internet Explorer and attachEvent (MDN)


这似乎是完全在 JavaScript 中检测 IE <= 8 的最有效方法 - 对于像我这样正在寻找方法的人来说非常有用。
伟大的!这也检测了我一直在寻找的 Quirks 模式下的 IE9。
尽管这是一个“易于使用”的解决方案,但它也存在一些风险。您公司中的任何人(不知道您的解决方案)都可以实现“addEventListener”或“attachEvent”来处理 IE 8 中缺少它的问题。然后,您的代码将停止工作。
E
EpokK

轻松检测 MSIE (v6 - v7 - v8 - v9 - v10 - v11):

if (navigator.userAgent.indexOf('MSIE') !== -1 || navigator.appVersion.indexOf('Trident/') > 0) {
   // MSIE
}

用于检测 IE10,因为它不支持条件注释。在 IE11 中不起作用,但 IE11 通常行为正常
最后是一个不讲关于使用特征检测并实际回答问题的答案。
i
iurii

这是 AngularJS checks 用于 IE 的方式

/**
 * documentMode is an IE-only property
 * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
 */
var msie = document.documentMode;

if (msie < 9) {
    // code for IE < 9
}

哇,这比所有有条件的评论都简单多了!没有这个限制?
根据文档,IE8+ 支持这个属性,所以我认为对于大多数情况来说应该足够了。
根据 MSDN 参考,“当当前文档尚未确定时,documentMode 返回零 (0) 值。这通常发生在加载文档时。”这是否意味着您可能无法在 中加载的脚本中获得有效响应?
我认为您可以通过在文档已加载时检查 window.onload 上的值来修复它。
哇!聪明的。谢谢!
M
Marat Tanalin

为了可靠地过滤 IE8 和更早版本,可以使用 checking global objects

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

@RajaKhoury - 如果尝试测试 IE<9 这很好 - if 条件将是错误的。
S
S.Serpooshan

使用特性检测检测 IE 版本(IE6+,IE6 之前的浏览器被检测为 6,非 IE 浏览器返回 null):

var ie = (function (){
    if (window.ActiveXObject === undefined) return null; //Not IE
    if (!window.XMLHttpRequest) return 6;
    if (!document.querySelector) return 7;
    if (!document.addEventListener) return 8;
    if (!window.atob) return 9;
    if (!document.__proto__) return 10;
    return 11;
})();

编辑:为方便起见,我创建了一个 bower/npm 存储库:ie-version

更新:

更紧凑的版本可以写成一行:

return window.ActiveXObject === undefined ? null : !window.XMLHttpRequest ? 6 : !document.querySelector ? 7 : !document.addEventListener ? 8 : !window.atob ? 9 : !document.__proto__ ? 10 : 11;

j
jKey

Detect IE in JS using conditional comments

// ----------------------------------------------------------
// A short snippet for detecting versions of IE in JavaScript
// without resorting to user-agent sniffing
// ----------------------------------------------------------
// If you're not in IE (or IE version is less than 5) then:
//     ie === undefined
// If you're in IE (>=5) then you can determine which version:
//     ie === 7; // IE7
// Thus, to detect IE:
//     if (ie) {}
// And to detect the version:
//     ie === 6 // IE6
//     ie > 7 // IE8, IE9 ...
//     ie < 9 // Anything less than IE9
// ----------------------------------------------------------

// UPDATE: Now using Live NodeList idea from @jdalton

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;

}());

这和我的回答差不多。
@TimDown:也许,但是这个答案功能更完整(它告诉您版本号),并且评论很好。此外,此答案开头的链接指向一个要点,其中包含一些信息丰富的评论和有关此技术的有趣变化。
@Alan:公平点。我根据问题定制了我的,但没有引用来源。
O
Owen

此函数将 IE 主要版本号作为整数返回,如果浏览器不是 Internet Explorer,则返回 undefined。与所有用户代理解决方案一样,这很容易受到用户代理欺骗(自版本 8 以来一直是 IE 的官方功能)。

function getIEVersion() {
    var match = navigator.userAgent.match(/(?:MSIE |Trident\/.*; rv:)(\d+)/);
    return match ? parseInt(match[1]) : undefined;
}

欧文,在实践中如何使用它?如何检索返回值?我尝试了 console.log(!!match && parseInt(match[1]))console.log(parseInt(match[1]))console.log(match),但没有任何结果。
通过调用函数本身 getIEVersion() 获取返回值。例如:if (getIEVersion() < 9) {/* IE 8 or below */} if (!getIEVersion()) {/* Not IE */}
i
iconMatrix

这对我有用。我将它用作重定向到一个页面,该页面解释了我们为什么不喜欢 < IE9 并提供指向我们喜欢的浏览器的链接。

<!--[if lt IE 9]>
<meta http-equiv="refresh" content="0;URL=http://google.com">
<![endif]-->

哦,那是一个讨厌的。我使用一种更友好的方法,显示一个带有 IE 警告外观的 div,当访问者点击它时,用户会转到 browsehappy.com
F
Fong-Wan Chau

您的代码可以进行检查,但正如您所想,如果有人尝试使用 IE v1 或 > v19 访问您的页面,则不会出现错误,因此使用 Regex 表达式进行检查可能更安全,如下面的代码:

var userAgent = navigator.userAgent.toLowerCase();
// Test if the browser is IE and check the version number is lower than 9
if (/msie/.test(userAgent) && 
    parseFloat((userAgent.match(/.*(?:rv|ie)[\/: ](.+?)([ \);]|$)/) || [])[1]) < 9) {
  // Navigate to error page
}

这不是一个好的答案。 UA 嗅探是不可靠的。更多信息在这里:modernizr.com/docs
@Jezen 有时 UA 嗅探是要走的路:github.com/Modernizr/Modernizr/issues/538
k
k0pernikus

从版本 10 开始,IE 不再支持条件注释,如 Microsoft reference page 中所述。

var ieDetector = function() { var browser = { // 浏览器对象 verIE: null, docModeIE: null, verIEtrue: null, verIE_ua: null }, tmp; tmp = document.documentMode;尝试 { document.documentMode = ""; } 捕捉 (e) {}; browser.isIE = typeof document.documentMode == "数字" || eval("/*@cc_on!@*/!1");尝试 { document.documentMode = tmp; } 捕捉 (e) {}; // 我们只让 IE 运行这段代码。 if (browser.isIE) { browser.verIE_ua = (/^(?:.*?[^a-zA-Z])??(?:MSIE|rv\s*\:)\s*(\d+\ .?\d*)/i).test(navigator.userAgent || "") ? parseFloat(RegExp.$1, 10) : null; var e, verTrueFloat, x, obj = document.createElement("div"), CLASSID = [ "{45EA75A0-A269-11D1-B5BF-0000F8051515}", // Internet Explorer 帮助 "{3AF36230-A269-11D1-B5BF- 0000F8051515}", // 离线浏览包 "{89820200-ECBD-11CF-8B85-00AA005B4383}" ];尝试 { obj.style.behavior = "url(#default#clientcaps)" } 捕捉 (e) {}; for (x = 0; x < CLASSID.length; x++) { try { browser.verIEtrue = obj.getComponentVersion(CLASSID[x], "componentid").replace(/,/g, "."); } 捕捉 (e) {};如果(browser.verIEtrue)中断; }; verTrueFloat = parseFloat(browser.verIEtrue || "0", 10); browser.docModeIE = 文档.documentMode || ((/back/i).test(document.compatMode || "") ? 5 : verTrueFloat) || browser.verIE_ua; browser.verIE = verTrueFloat || browser.docModeIE; };返回 { isIE: browser.isIE, 版本: browser.verIE }; }(); document.write('isIE: ' + ieDetector.isIE + "
"); document.write('IE 版本号:' + ieDetector.Version);

然后使用:

if((ieDetector.isIE) && (ieDetector.Version <= 9))
{

}

这是唯一在整个网络上都有效的东西,至少是我尝试过的那些巨大的东西……谢谢 ;)
此代码很好,但无法检测兼容性视图模式。我在 IE 11 上使用 IE 8 中的兼容性视图,这段代码仍然给出 version 11 编辑:这段代码太棒了!哈哈,它给了一个里面所有东西的对象。版本是 11,但 docModeIR 等于 9。谢谢!
C
Community

对于即 10 和 11:

您可以使用js并在html中添加一个类来保持conditional comments的标准:

  var ua = navigator.userAgent,
      doc = document.documentElement;

  if ((ua.match(/MSIE 10.0/i))) {
    doc.className = doc.className + " ie10";

  } else if((ua.match(/rv:11.0/i))){
    doc.className = doc.className + " ie11";
  }

或者使用像 bowser 这样的库:

https://github.com/ded/bowser

或用于特征检测的modernizr:

http://modernizr.com/


我尝试了一些脚本和解决方案,但没有任何效果。然后我在项目中包含了 bowser,它就可以工作了。所以一个建议鲍泽。
T
Timothy Perez

这已经被回答到死了,但这就是你所需要的。

!!navigator.userAgent.match(/msie\s[5-8]/i)

此外,这里是一个沙盒,显示了针对最常见的 IE 用户代理字符串的正则表达式模式:regex101.com/r/lC6oP3/1
@alessadro - 但它应该是,不是吗? OP 想测试 < 9 ...
B
Berezh
var Browser = new function () {
    var self = this;
    var nav = navigator.userAgent.toLowerCase();
    if (nav.indexOf('msie') != -1) {
        self.ie = {
            version: toFloat(nav.split('msie')[1])
        };
    };
};


if(Browser.ie && Browser.ie.version > 9)
{
    // do something
}

B
Brian

要检测 Internet Explorer 10|11,您可以在 body 标记之后立即使用这个小脚本:

在我的情况下,我使用加载在 head 中的 jQuery 库。

<!DOCTYPE HTML>
<html>
<head>
    <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
    <script>if (navigator.appVersion.indexOf('Trident/') != -1) $("body").addClass("ie10");</script>
</body>
</html>

我喜欢这个谢谢,我只需要检测 10 或 11,因为我不支持以前的版本
IE9 也是三叉戟,但对 CSS 的支持不一样。您的检测认为至少为 10,但这是不正确的。
A
AHH

根据Microsoft,以下是最好的解决方案,也很简单:

function getInternetExplorerVersion()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
    var rv = -1; // Return value assumes failure.
    if (navigator.appName == 'Microsoft Internet Explorer')
    {
        var ua = navigator.userAgent;
        var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
        if (re.exec(ua) != null)
            rv = parseFloat( RegExp.$1 );
    }
    return rv;
}

function checkVersion()
{
    var msg = "You're not using Internet Explorer.";
    var ver = getInternetExplorerVersion();

    if ( ver > -1 )
    {
        if ( ver >= 8.0 ) 
            msg = "You're using a recent copy of Internet Explorer."
        else
            msg = "You should upgrade your copy of Internet Explorer.";
      }
    alert( msg );
}

事实上,以防万一其他人在这里尝试使用上述内容,稍后答案中的代码确实适用于 IE11(stackoverflow.com/a/26375930/1129926)。但请注意,它适用于 IE12 等吗?最重要的是最好将这些视为临时黑客,并且随着新浏览器版本的发布(我什至不会提及 Edge),它们可能会在以后失败。
P
PressingOnAlways

我发现用于检查 IE 版本的最全面的 JS 脚本是 http://www.pinlady.net/PluginDetect/IE/。整个库位于 http://www.pinlady.net/PluginDetect/Browsers/

IE10 不再支持条件语句。

在 IE11 中,用户代理不再包含 MSIE。此外,使用用户代理是不可靠的,因为它可以被修改。

使用 PluginDetect JS 脚本,您可以使用针对特定 IE 版本的非常具体且精心设计的代码来检测 IE 并检测确切的版本。当您确切关心您正在使用的浏览器版本时,这非常有用。


J
John Munsch

我将建议不要无数次重写此代码。我建议您使用 Conditionizr 库 (http://conditionizr.com/),它能够测试特定 IE 版本以及其他浏览器、操作系统,甚至是否存在 Retina 显示器。

仅包含您需要的特定测试的代码,并且您还可以获得经过多次迭代的测试库的好处(并且可以在不破坏代码的情况下轻松升级)。

它还与 Modernizr 很好地结合在一起,它可以处理所有那些你最好测试特定功能而不是特定浏览器的情况。


J
Julio Cesar Boaroli

我喜欢这样:

<script>
   function isIE () {
       var myNav = navigator.userAgent.toLowerCase();
       return (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false;
   }    
   var ua = window.navigator.userAgent;
   //Internet Explorer | if | 9-11

   if (isIE () == 9) {
       alert("Shut down this junk! | IE 9");
   } else if (isIE () == 10){
       alert("Shut down this junk! | IE 10");
   } else if (ua.indexOf("Trident/7.0") > 0) {
       alert("Shut down this junk! | IE 11");
   }else{
       alert("Thank god it's not IE!");
   }

</script>

j
jtbr

这种检测 IE 的方法结合了 jKey 使用条件注释的答案和 Owen 使用用户代理的答案的优点并避免了缺点。

jKey 的方法适用于版本 9,并且不受 IE 8 和 9 中用户代理欺骗的影响。

Owen 的方法在 IE 5 和 6(报告 7)上可能会失败,并且容易受到 UA 欺骗,但它可以检测到 IE 版本 >= 10(现在还包括 12,这是 Owen 的回答之后的版本)。 //------------------------------------------------ ---------- // 用于检测 IE 版本的简短片段 // ---------------------------- ------------------------------ // 如果你不在 IE 中(或者 IE 版本低于 5)那么: // ie === undefined // 因此,检测 IE: // if (ie) {} // 并检测版本: // ie === 6 // IE6 // ie > 7 // IE8, IE9 ... // -------------------------------------------- -------------- var ie = (function(){ var v = 3, div = document.createElement('div'), all = div.getElementsByTagName('i'); 而( div.innerHTML = '', all[0] ); if ( v <= 4) { // 使用用户代理检查 IE>9 var match = navigator.userAgent.match(/(?:MSIE |Trident\/.*; rv:|Edge\/)(\d+)/) ; v = 匹配 ? parseInt(match[1]) : undefined; } return v; }());

这可用于为包含 IE 版本的文档设置有用的类:

    if (ie) {
        document.documentElement.className += ' ie' + ie;
        if (ie < 9)
            document.documentElement.className += ' ieLT9';
    }

请注意,如果 IE 处于兼容模式,它会检测正在使用的兼容模式。另请注意,IE 版本对旧版本(<10)最有用;更高的版本更符合标准,最好使用诸如modernizr.js之类的东西来检查功能。


d
danrichards

我为此做了一个方便的下划线混合。

_.isIE();        // Any version of IE?
_.isIE(9);       // IE 9?
_.isIE([7,8,9]); // IE 7, 8 or 9?

_.mixin({ isIE: function(mixed) { if (_.isUndefined(mixed)) { mixed = [7, 8, 9, 10, 11]; } else if (_.isNumber(mixed)) { mixed = [混合]; } for (var j = 0; j < mixed.length; j++) { var re; switch (mixed[j]) { case 11: re = /Trident.*rv\:11\./g;中断;案例 10:re = /MSIE\s10\./g;中断;案例 9:re = /MSIE\s9\./g;中断;案例 8:re = /MSIE\s8\./g;中断;案例 7: re = /MSIE\s7\./g; break; } if (!!window.navigator.userAgent.match(re)) { return true; } } return false; } });控制台.log(_.isIE()); console.log(_.isIE([7, 8, 9]));控制台.log(_.isIE(11));


G
Giacomo

或者干脆

//   IE 10: ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)'; 
//   IE 11: ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko'; 
// Edge 12: ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0'; 
// Edge 13: ua = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36 Edge/13.10586'; 

var isIE = navigator.userAgent.match(/MSIE|Trident|Edge/)
var IEVersion = ((navigator.userAgent.match(/(?:MSIE |Trident.*rv:|Edge\/)(\d+(\.\d+)?)/)) || []) [1]

R
Ric

我意识到我在这里聚会有点晚了,但我一直在检查一种简单的单行方式来提供有关浏览器是否是 IE 以及它是 10 以后的版本的反馈。我没有为版本 11 编写此代码,因此可能需要对此进行一些修改。

然而,这是代码,它作为一个具有属性和方法的对象工作,并且依赖于对象检测而不是抓取导航器对象(它存在大量缺陷,因为它可以被欺骗)。

var isIE = { browser:/*@cc_on!@*/false, detectedVersion: function () { return (typeof window.atob !== "undefined") ? 10 : (typeof document.addEventListener !== "undefined") ? 9 : (typeof document.querySelector !== "undefined") ? 8 : (typeof window.XMLHttpRequest !== "undefined") ? 7 : (typeof document.compatMode !== "undefined") ? 6 : 5; } };

用法是 isIE.browser 一个返回布尔值的属性并依赖于条件注释方法 isIE.detectedVersion() 返回一个介于 5 和 10 之间的数字。我假设任何低于 6 的值,并且您处于严肃的老派领域,并且你会比一个班轮和任何高于 10 的东西更强壮,你会进入更新的领域。我读过一些关于 IE11 不支持条件评论的内容,但我还没有完全调查,可能是以后的日期。

无论如何,就目前而言,它会涵盖 IE 浏览器和版本检测的基础知识。它远非完美,但它很小且易于修改。

仅供参考,如果有人对如何实际实现这一点有任何疑问,那么以下条件应该会有所帮助。

var isIE = { browser:/*@cc_on!@*/false, detectedVersion: function () { return (typeof window.atob !== "undefined") ? 10 : (typeof document.addEventListener !== "undefined") ? 9 : (typeof document.querySelector !== "undefined") ? 8 : (typeof window.XMLHttpRequest !== "undefined") ? 7 : (typeof document.compatMode !== "undefined") ? 6 : 5; } };

/* testing IE */

if (isIE.browser) {
  alert("This is an IE browser, with a detected version of : " + isIE.detectedVersion());
}

F
Frank Conijn - Support Ukraine

检测 IE 及其版本再简单不过了,您只需要一点原生/原版 Javascript:

var uA = navigator.userAgent;
var browser = null;
var ieVersion = null;

if (uA.indexOf('MSIE 6') >= 0) {
    browser = 'IE';
    ieVersion = 6;
}
if (uA.indexOf('MSIE 7') >= 0) {
    browser = 'IE';
    ieVersion = 7;
}
if (document.documentMode) { // as of IE8
    browser = 'IE';
    ieVersion = document.documentMode;
}

这是一种使用它的方法:

if (browser == 'IE' && ieVersion <= 9) 
    document.documentElement.className += ' ie9-';

.

适用于所有 IE 版本,包括较低兼容性视图/模式下的更高版本,并且 documentMode 是 IE 专有的。


N
Nimesh

如果您需要选择 IE 浏览器版本,则可以按照以下代码进行操作。此代码适用于 IE6 到 IE11 版本

<!DOCTYPE html>
<html>
<body>

<p>Click on Try button to check IE Browser version.</p>

<button onclick="getInternetExplorerVersion()">Try it</button>

<p id="demo"></p>

<script>
function getInternetExplorerVersion() {
   var ua = window.navigator.userAgent;
        var msie = ua.indexOf("MSIE ");
        var rv = -1;

        if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))      // If Internet Explorer, return version number
        {               
            if (isNaN(parseInt(ua.substring(msie + 5, ua.indexOf(".", msie))))) {
                //For IE 11 >
                if (navigator.appName == 'Netscape') {
                    var ua = navigator.userAgent;
                    var re = new RegExp("Trident/.*rv:([0-9]{1,}[\.0-9]{0,})");
                    if (re.exec(ua) != null) {
                        rv = parseFloat(RegExp.$1);
                        alert(rv);
                    }
                }
                else {
                    alert('otherbrowser');
                }
            }
            else {
                //For < IE11
                alert(parseInt(ua.substring(msie + 5, ua.indexOf(".", msie))));
            }
            return false;
        }}
</script>

</body>
</html>

x
xicooc

Window 运行 IE10 会自动更新到 IE11+ 并且会标准化 W3C

现在,我们不需要支持 IE8-

    <!DOCTYPE html>
    <!--[if lt IE 9]><html class="ie ie8"><![endif]-->
    <!--[if IE 9]><html class="ie ie9"><![endif]-->
    <!--[if (gt IE 9)|!(IE)]><!--><html><!--<![endif]-->
    <head>
        ...
        <!--[if lt IE 8]><meta http-equiv="Refresh" content="0;url=/error-browser.html"><![endif]--
        ...
    </head>

x
xicooc
var isIE9OrBelow = function()
{
   return /MSIE\s/.test(navigator.userAgent) && parseFloat(navigator.appVersion.split("MSIE")[1]) < 10;
}

B
Bruce
if (!document.addEventListener) {
    // ie8
} else if (!window.btoa) {
    // ie9
}
// others