判断是否为IE浏览器:
function isIE() {
if(!!window.ActiveXObject || "ActiveXObject" in window) {
return true;
}else{
return false;
}
}
注:
-
IE早些版本时,IE10及以下,window.ActiveXObject 返回一个对象,!window.ActiveXObject则变为false,!!window.ActiveXObject则为true,因为是或||符号后续无需再判断,返回true。
-
IE11中,window.ActiveXObject返回undefine,!window.ActiveXObject则变成了true,!!window.ActiveXObject则变成了false,进入 "window.ActiveXObject" in window判断,该判断条件在IE11下返回true。
-
其他非IE浏览器,如chrome,firefox,window.ActiveXObject都是undefine,!!window.ActiveXObject都是返回的false,
而 "window.ActiveXObject" in window也是返回false,因此上述判断函数在非IE浏览器中返回的都是false。
IE 11的userAgent为:"Mozilla/5.0 (Windows NT 6.1;WOW64;Trident/7.0;SLCC2;.NET CLR 2.0.50727;.NET CLR 3.5.30729;.NET CLR 3.0.30729;Media Center PC6.0;.NET4.0C;.NET4.0E;Shuame;rv:11.0) like Gecko"。
明显之前根据MSIE的方式来判断,对IE11是失效的。
判断IE版本:
if(navigator.appName == "Microsoft Internet Explorer" && navigator.appVersion.match(/6./i)=="6."){
alert("IE 6");
} else if(navigator.appName == "Microsoft Internet Explorer" && navigator.appVersion.match(/7./i)=="7."){
alert("IE 7");
} else if(navigator.appName == "Microsoft Internet Explorer" && navigator.appVersion.match(/8./i)=="8."){
alert("IE 8");
} else if(navigator.appName == "Microsoft Internet Explorer" && navigator.appVersion.match(/9./i)=="9."){
alert("IE 9");
}
判断浏览器类型:
if(navigator.userAgent.indexOf("Opera") != -1) {
alert('Opera');
} else if(navigator.userAgent.indexOf("MSIE") != -1) {
alert('Internet Explorer'); //MSIE对IE11失效
} else if(navigator.userAgent.indexOf("Firefox") != -1) {
alert('Firefox');
}else if(navigator.userAgent.indexOf("Netscape") != -1) {
alert('Netscape');
} else if(navigator.userAgent.indexOf("Safari") != -1) {
alert('Safari');
}else{
alert('无法识别的浏览器。');
}