回答

6

通過James Padolsey退房this snippet

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

}()); 

之後,你可以使用這樣的:

if (ie == 9) { 
    // It’s IE9! 
    // Insert your code here 
} 

這裏的好處是,它並沒有嗅出UA字符串(,本身並不可靠) - 相反,它使用條件註釋,它在IE中可靠地工作。

這可以用來檢測IE5-9。

+0

當我在ie9中測試它時,它會給我「7」。 – 2012-02-01 10:57:08

+1

爲此+1,這是我會發布,似乎不那麼知名。有一點需要注意的是,IE 10不會支持條件註釋,所以這個技巧在IE的未來版本中不起作用(請參閱http://blogs.msdn.com/b/ie/archive/2011/07/06/html5 -parsing-in-ie10.aspx) – 2012-02-01 10:58:45

+0

它無法正常工作:( – 2012-02-01 11:00:30

0

不是100%肯定這是你問什麼,但如果你想檢測一下,你可以做訪問者的瀏覽器的信息查詢navigator.appVersion

例子:

<div id="example"></div> 

<script type="text/javascript"> 

txt = "<p>Browser CodeName: " + navigator.appCodeName + "</p>"; 
txt+= "<p>Browser Name: " + navigator.appName + "</p>"; 
txt+= "<p>Browser Version: " + navigator.appVersion + "</p>"; 
txt+= "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>"; 
txt+= "<p>Platform: " + navigator.platform + "</p>"; 
txt+= "<p>User-agent header: " + navigator.userAgent + "</p>"; 

document.getElementById("example").innerHTML=txt; 

</script> 
+0

這是不建議的方式看看這裏http://www.quirksmode.org/js/support.html – 2012-02-01 10:57:43

0

使用屬性在每個版本中引入的IE window object的區分IE版本:

  • IE> = 7:("onpropertychange" in document) && (!!window.XMLHttpRequest)

  • IE> = 8:("onpropertychange" in document) && (!!window.XDomainRequest)

  • IE> = 9:("onpropertychange" in document) && (!!window.innerWidth)

  • IE> = 10:("onpropertychange" in document) && (!!window.matchMedia)

  • IE> = 11:(!!window.msMatchMedia) && (!window.doScroll)