当我想检测IE时,我使用以下代码:

function getInternetExplorerVersion()
{
  var rv = -1;
  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 )
  {
    msg = "You are using IE " + ver;
  }
  alert( msg );
}

但是IE11返回“您没有使用Internet Explorer”。我如何检测它?


当前回答

解决方案:

function GetIEVersion() { var sAgent = window.navigator.userAgent; var Idx = sAgent.indexOf("MSIE"); // If IE, return version number. if (Idx > 0) return parseInt(sAgent.substring(Idx+ 5, sAgent.indexOf(".", Idx))); // If IE 11 then look for Updated user agent string. else if (!!navigator.userAgent.match(/Trident\/7\./)) return 11; else return 0; //It is not IE } if ((GetIEVersion() > 0) || (navigator.userAgent.toLowerCase().indexOf('firefox') > -1)){ alert("This is IE " + GetIEVersion()); }else { alert("This no is IE "); }

其他回答

这似乎是一种更好的方法。如果没有匹配,"indexOf"返回-1。它不会覆盖主体上现有的类,只是添加它们。

// add a class on the body ie IE 10/11
var uA = navigator.userAgent;
if(uA.indexOf('Trident') != -1 && uA.indexOf('rv:11') != -1){
    document.body.className = document.body.className+' ie11';
}
if(uA.indexOf('Trident') != -1 && uA.indexOf('MSIE 10.0') != -1){
    document.body.className = document.body.className+' ie10';
}

坦率地说,我会说使用你需要的库(比如platform.js)。在某些时候,事情会发生变化,库将为这些变化做好准备,使用正则表达式的手动解析将失败。

感谢上帝IE消失了…

我用了一个更简单的方法:

导航器全局对象有一个属性touchpoints,在ie11中称为msMaxTouchPoints tho。

所以如果你寻找:

navigator.msMaxTouchPoints !== void 0 

你会找到Internet Explorer 11。

解决方案:

function GetIEVersion() { var sAgent = window.navigator.userAgent; var Idx = sAgent.indexOf("MSIE"); // If IE, return version number. if (Idx > 0) return parseInt(sAgent.substring(Idx+ 5, sAgent.indexOf(".", Idx))); // If IE 11 then look for Updated user agent string. else if (!!navigator.userAgent.match(/Trident\/7\./)) return 11; else return 0; //It is not IE } if ((GetIEVersion() > 0) || (navigator.userAgent.toLowerCase().indexOf('firefox') > -1)){ alert("This is IE " + GetIEVersion()); }else { alert("This no is IE "); }

使用MSInputMethodContext作为特性检测检查的一部分。例如:

//Appends true for IE11, false otherwise
window.location.hash = !!window.MSInputMethodContext && !!document.documentMode;

参考文献

MSInputMethodContext对象 输入法编辑器API 我希望在IE12中看到什么:Internet Explorer 12的错误修复和新功能的愿望清单 打印稿/ lib.dom.d。·微软/TypeScript IE DOM api