【问题标题】:Detect IE version (prior to v9) in JavaScript在 JavaScript 中检测 IE 版本(v9 之前)
【发布时间】:2012-06-13 11:08:54
【问题描述】:

如果我们网站的用户使用的是 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
    }
}

这段代码能解决问题吗?

阻止一些可能会出现在我面前的cmets:

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

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

【问题讨论】:

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

标签: javascript internet-explorer user-agent browser-detection


【解决方案1】:

您的代码可以进行检查,但正如您所想,如果有人尝试使用 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
}

【讨论】:

【解决方案2】:

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

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

Legacy Internet Explorer and attachEvent (MDN)

【讨论】:

  • 这似乎是完全在 JavaScript 中检测 IE
  • 太棒了!这也检测了我一直在寻找的 Quirks 模式下的 IE9。
  • 虽然这是一个“易于使用”的解决方案,但它也存在一些风险。您公司中的任何人(不知道您的解决方案)都可以实现“addEventListener”或“attachEvent”来处理 IE 8 中缺少它的问题。然后,您的代码将停止工作。
【解决方案3】:

这是我的首选方式。它提供了最大的控制。 (注意:条件语句仅在 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:@ 987654322@
  • 我在 w3 html 验证器上收到一个错误:Error: Saw &lt;!-- within a comment. Probable cause: Nested comment (not allowed). At line 5, column 21 if gt IE 8]&gt;&lt;!--&gt;&lt;html
【解决方案4】:

使用条件 cmets。您正在尝试检测 IE = 10 和非 IE)中,cmets 将被视为普通 HTML cmets,它们就是这样。

示例 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 上对其进行了测试; Mac OS X Snow Leopard 与 Safari 5.1、Firefox 28.0、Chrome 33.0 和 Opera 20.0; iPhone 5 移动版 Safari;和安卓三星 Galaxy Tab 2 10.1 4.0。不出所料,只有 IE8 报告它是 IeLessThan9。不错!
【解决方案5】:

这对我有用。我将它用作重定向到一个页面,该页面解释了我们为什么不喜欢

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

【讨论】:

  • 哦,这很糟糕。我使用一种更友好的方法,显示一个带有 IE 警告外观的 div,当访问者点击它时,用户会转到 browsehappy.com
【解决方案6】:

返回 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 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 似乎是正确的做法。
【解决方案7】:

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:也许,但这个答案功能更完整(它告诉你版本号),并且评论很好。此外,此答案开头的链接指向一个 Gist,其中包含几个信息丰富的 cmets 和该技术的有趣变体。
  • @Alan:公平点。我根据问题定制了我的,但没有引用来源。
【解决方案8】:

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

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

【讨论】:

  • 对于检测 IE10 很有用,因为它不支持条件 cmets。在 IE11 中不起作用,但 IE11 通常行为正常
  • 终于有了一个不讲关于使用特征检测并实际回答问题的答案。
【解决方案9】:
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
}

【讨论】:

    【解决方案10】:

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

    在 IE10 中,不再支持条件语句。

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

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

    【讨论】:

      【解决方案11】:

      对于 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,它就可以工作了。所以建议鲍泽。
      【解决方案12】:

      根据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),它们可能会在以后失败。
      【解决方案13】:

      此函数将 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 &amp;&amp; parseInt(match[1]))console.log(parseInt(match[1]))console.log(match),但没有任何结果。
      • 通过调用函数本身getIEVersion()获取返回值。例如:if (getIEVersion() &lt; 9) {/* IE 8 or below */}if (!getIEVersion()) {/* Not IE */}
      【解决方案14】:

      我意识到我在这里聚会有点晚了,但我一直在检查一种简单的单行方式来提供有关浏览器是否为 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 一个返回布尔值并依赖于条件 cmets 方法的属性 isIE.detectedVersion() 返回一个介于 5 和 10 之间的数字。我假设任何低于 6 的值,并且你已经很老了学校领域,你会比一个班轮和任何高于 10 的东西更强壮,你会进入新的领域。我读过一些关于 IE11 不支持条件 cmets 的内容,但我还没有完全调查,可能是以后的日期。

      不管怎样,对于一个单行来说,它将涵盖 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());
      }
      

      【讨论】:

        【解决方案15】:

        检测 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 专有的。

        【讨论】:

          【解决方案16】:

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

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

          【讨论】:

          【解决方案17】:

          要检测 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,但这是不正确的。
          【解决方案18】:

          使用特征检测检测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;
          

          【讨论】:

            【解决方案19】:

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

            var ieDetector = function() {
              var browser = { // browser object
            
                  verIE: null,
                  docModeIE: null,
                  verIEtrue: null,
                  verIE_ua: null
            
                },
                tmp;
            
              tmp = document.documentMode;
              try {
                document.documentMode = "";
              } catch (e) {};
            
              browser.isIE = typeof document.documentMode == "number" || eval("/*@cc_on!@*/!1");
              try {
                document.documentMode = tmp;
              } catch (e) {};
            
              // We only let IE run this code.
              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 Help
                    "{3AF36230-A269-11D1-B5BF-0000F8051515}", // Offline Browsing Pack
                    "{89820200-ECBD-11CF-8B85-00AA005B4383}"
                  ];
            
                try {
                  obj.style.behavior = "url(#default#clientcaps)"
                } catch (e) {};
            
                for (x = 0; x < CLASSID.length; x++) {
                  try {
                    browser.verIEtrue = obj.getComponentVersion(CLASSID[x], "componentid").replace(/,/g, ".");
                  } catch (e) {};
            
                  if (browser.verIEtrue) break;
            
                };
                verTrueFloat = parseFloat(browser.verIEtrue || "0", 10);
                browser.docModeIE = document.documentMode ||
                  ((/back/i).test(document.compatMode || "") ? 5 : verTrueFloat) ||
                  browser.verIE_ua;
                browser.verIE = verTrueFloat || browser.docModeIE;
              };
            
              return {
                isIE: browser.isIE,
                Version: browser.verIE
              };
            
            }();
            
            document.write('isIE: ' + ieDetector.isIE + "<br />");
            document.write('IE Version Number: ' + ieDetector.Version);

            然后使用:

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

            【讨论】:

            • 这是唯一能在整个网络上运行的东西,至少是我尝试过的那些巨大的东西......谢谢 ;)
            • 这段代码不错,但无法检测兼容性视图模式。我在 IE 11 上使用 IE 8 中的兼容性视图,这段代码仍然给出version 11 编辑:这段代码太棒了!哈哈,它给了一个里面所有东西的对象。版本是 11,但 docModeIR 等于 9。谢谢!
            【解决方案20】:

            如果您需要选择 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>
            

            【讨论】:

              【解决方案21】:

              使用 JQuery:

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

              使用 C#:

              var browser = Request.Browser.Browser;
              

              【讨论】:

              • 这不是纯 JavaScript
              【解决方案22】:

              运行 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>
              

              【讨论】:

                【解决方案23】:

                简单的解决方案停止思考浏览器并使用年份。

                var year = eval(today.getYear());
                if(year < 1900 )
                 {alert('Good to go: All browsers and IE 9 & >');}
                else
                 {alert('Get with it and upgrade your IE to 9 or >');}
                

                【讨论】:

                • 请您解释一下为什么您认为这会起作用。
                • 任何浏览器都会返回此错误:today is not defined。还有你为什么用年份来检测IE版本?
                【解决方案24】:
                var isIE9OrBelow = function()
                {
                   return /MSIE\s/.test(navigator.userAgent) && parseFloat(navigator.appVersion.split("MSIE")[1]) < 10;
                }
                

                【讨论】:

                  【解决方案25】:

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

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

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

                  【讨论】:

                    【解决方案26】:

                    这是 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 上的值来修复它。
                    • 哇!聪明的。谢谢!
                    【解决方案27】:

                    我喜欢这样:

                    <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>
                    

                    【讨论】:

                      【解决方案28】:

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

                      • jKey 的方法适用于版本 9,并且不受 IE 8 和 9 中用户代理欺骗的影响。
                      • Owen 的方法在 IE 5 和 6(报告 7)上可能会失败,并且容易受到 UA 欺骗,但它可以检测到 IE 版本 >= 10(现在还包括 12,这是 Owen 的回答之后的版本)。

                        // ----------------------------------------------------------
                        // A short snippet for detecting versions of IE
                        // ----------------------------------------------------------
                        // If you're not in IE (or IE version is less than 5) then:
                        //     ie === undefined
                        // Thus, to detect IE:
                        //     if (ie) {}
                        // And to detect the version:
                        //     ie === 6 // IE6
                        //     ie > 7 // IE8, IE9 ...
                        // ----------------------------------------------------------
                        var ie = (function(){
                            var v = 3,
                                div = document.createElement('div'),
                                all = div.getElementsByTagName('i');
                        
                            while (
                                div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
                                all[0]
                            );
                            if (v <= 4) { // Check for IE>9 using user agent
                                var match = navigator.userAgent.match(/(?:MSIE |Trident\/.*; rv:|Edge\/)(\d+)/);
                                v = match ? parseInt(match[1]) : undefined;
                            }
                            return v;
                        }());
                        

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

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

                      请注意,如果 IE 处于兼容模式,它会检测正在使用的兼容模式。另请注意,IE 版本对旧版本(

                      【讨论】:

                        【解决方案29】:
                        if (!document.addEventListener) {
                            // ie8
                        } else if (!window.btoa) {
                            // ie9
                        }
                        // others
                        

                        【讨论】:

                          【解决方案30】:
                          // Detect ie <= 10
                          var ie = /MSIE ([0-9]+)/g.exec(window.navigator.userAgent)[1] || undefined;
                          
                          console.log(ie);
                          // Return version ie or undefined if not ie or ie > 10
                          

                          【讨论】:

                            猜你喜欢
                            • 2012-02-03
                            • 2011-11-06
                            • 1970-01-01
                            • 1970-01-01
                            • 1970-01-01
                            • 2012-08-11
                            • 1970-01-01
                            • 2013-09-08
                            • 2011-03-14
                            相关资源
                            最近更新 更多