【问题标题】:detect Internet Explorer (working with IE10+ too!)检测 Internet Explorer(也可以使用 IE10+!)
【发布时间】:2013-08-24 18:02:53
【问题描述】:

Conditional comments have been deprecated since IE10 破坏了一些用于检测当前 Web 浏览器是否为 IE 的遗留代码。见https://gist.github.com/padolsey/527683

我正在寻找适用于所有 Internet Explorer 版本(不仅是 IE9 及以下版本)的解决方案。

谢谢

【问题讨论】:

标签: javascript internet-explorer cross-browser frontend


【解决方案1】:

https://gist.github.com/padolsey/527683 上的“ecstaticpeon”发表评论后,我发现这是可行的。

http://jsfiddle.net/P5z4N/4/自己尝试一下

var ie_version = (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;
}());
/*@cc_on
if (typeof(ie_version) == 'undefined') {
    ie_version = parseInt(@_jscript_version);
}
@*/

下面的 javascript 似乎也可以工作:

试试http://jsfiddle.net/e8G3S/1/

// Returns the version of Internet Explorer or a -1 (indicating the use of another browser)
function getInternetExplorerVersion(){
  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 displayAlert(){
  var msg = "You're not using Internet Explorer.";
  var ver = getInternetExplorerVersion();
  if ( ver > -1 ){
    if ( ver <= 8.0 ){
      msg = "You're using Internet Explorer 8 or below" ;
    }
    else if ( ver >= 9.0 && ver < 10.0 ){
      msg = "You're using IE 9 or above";
    }
    else{
      msg = "You're using IE 10 or above"; 
    }
  }
  alert( msg );

【讨论】:

  • 这些策略在 IE11 及以后的版本中会失效。
  • @EricLaw:你能解释一下原因吗?
  • 因为 IE 团队故意破坏了这些方法,因为它们是互操作性问题的常见来源。具体来说,IE11 的 AppName 不是“Microsoft Internet Explorer”,默认的用户代理字符串不再包含“MSIE”。
  • @EricLaw:很有趣。感谢您的提醒。
猜你喜欢
  • 2019-11-20
  • 1970-01-01
  • 2023-03-25
  • 1970-01-01
  • 1970-01-01
  • 2012-12-10
  • 1970-01-01
相关资源
最近更新 更多