问题
I just want to target only IE10 and below versions IE browsers. Please help me for this. I have tried below code
var userAgent = navigator.userAgent;
var regexIe8 = new RegExp("Trident(\/4.0)|(Trident\/5.0)");
if (regexIe8.test(userAgent)) {
alert("test1");
}
else {
alert("test2");
}
回答1:
In Internet Explorer 11, Microsoft took out the "MSIE", so it now looks like this:
Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko
So you could just check for the presence of "MSIE" to tell you if it's an old version.
if (navigator.userAgent.indexOf("MSIE") >= 0) {
document.write("You are using an unsupported version of Internet Explorer. Please upgrade to Internet Explorer 11 or use a different web browser.");
}
Just note that if Internet Explorer is in compatibility view, and you haven't specified an X-UA-Compatible header, it will identify itself as IE 7 and act like it too.
回答2:
Using conditional comments instead of Javascript detection:
<!--[if IE]>
<div class='old-browser'>You are running an un-supported version of Internet Explorer. Please upgrade</div>
<![endif]-->
Just stick that directly in your page where you want the notification to appear. No Javascript required (although you can, of course, use JS here if you want to).
Note that IE10 no longer supports conditional comments, so you just need to check [if IE]
to catch all versions of IE up to IE9.
回答3:
Here is a great CodePen with a complete solution for all versions of IE and Edge:
https://codepen.io/gapcode/pen/vEJNZN
From the linke, here are examples of the various values of window.navigator.userAgent
:
// IE 10
// ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)';
// IE 11
// ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';
// Edge 12 (Spartan)
// ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0';
// Edge 13
// ua = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36 Edge/13.10586';
来源:https://stackoverflow.com/questions/34758504/ie10-and-below-browser-detection