在javascript代码中检查IE11

在javascript代码中检查IE11,javascript,Javascript,我正在检查IE11的脚本,但下面的代码似乎不起作用,它返回false function isIE () { var myNav = navigator.userAgent.toLowerCase(); alert(myNav); return (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false; } alert(isIE());

我正在检查IE11的脚本,但下面的代码似乎不起作用,它返回false

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


任何人都可以更新此功能以检测IE11吗不再建议检查特定浏览器-功能检测通常更有用。如果您真的需要检测IE11,以下页面在检测IE x.x部分下有一个示例脚本:

如果此链接将来消失,脚本如下所示:

//userAgent in IE7 WinXP returns: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727)
//userAgent in IE11 Win7 returns: Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko

if (navigator.userAgent.indexOf('MSIE') != -1)
 var detectIEregexp = /MSIE (\d+\.\d+);/ //test for MSIE x.x
else // if no "MSIE" string in userAgent
 var detectIEregexp = /Trident.*rv[ :]*(\d+\.\d+)/ //test for rv:x.x or rv x.x where Trident string exists

if (detectIEregexp.test(navigator.userAgent)){ //if some form of IE
 var ieversion=new Number(RegExp.$1) // capture x.x portion and store as a number
 if (ieversion>=12)
  document.write("You're using IE12 or above")
 else if (ieversion>=11)
  document.write("You're using IE11 or above")
 else if (ieversion>=10)
  document.write("You're using IE10 or above")
 else if (ieversion>=9)
  document.write("You're using IE9 or above")
 else if (ieversion>=8)
  document.write("You're using IE8 or above")
 else if (ieversion>=7)
  document.write("You're using IE7.x")
 else if (ieversion>=6)
  document.write("You're using IE6.x")
 else if (ieversion>=5)
  document.write("You're using IE5.x")
}
else{
 document.write("n/a")
}
因此,要替换函数,您可以使用以下内容:

function isIE() {

    if (navigator.userAgent.indexOf('MSIE') != -1)
        return true;

    var detectIEregexp = /Trident.*rv[ :]*(\d+\.\d+)/   
    return detectIEregexp.test(navigator.userAgent);
}
适用于IE10及以下

myNav.indexOf('MSIE ') != -1
对于IE11

myNav.indexOf('Trident/') != -1
对于IE12

myNav.indexOf('Edge/') != -1
更新后的函数如下所示

function isIE () {
    var myNav = navigator.userAgent;
    return (myNav.indexOf('MSIE ') != -1 || myNav.indexOf('Trident/') != -1 || myNav.indexOf('Edge/') != -1);
}

为什么浏览器嗅探?重复问题:另外,请参阅处理IE10+的信息。编辑答案以包含简单的isIE功能。
function isIE () {
    var myNav = navigator.userAgent;
    return (myNav.indexOf('MSIE ') != -1 || myNav.indexOf('Trident/') != -1 || myNav.indexOf('Edge/') != -1);
}