阅读这篇文章,我发现了如下代码:
if ('v'=='\v') { // Note: IE listens on document
document.attachEvent('onstorage', onStorage, false);
}
这个方法
'v'=='\v'
是一种好的想法吗?这是检测IE最短的方法吗?阅读这篇文章,我发现了如下代码:
if ('v'=='\v') { // Note: IE listens on document
document.attachEvent('onstorage', onStorage, false);
}
'v'=='\v'
是一种好的想法吗?这是检测IE最短的方法吗?你可以通过以下方式检查Trident,即IE的引擎:
var trident = !!window.ActiveXObject;
根据MSDN的说明,该代码仅在IE中受支持。
编辑:
注意:上述代码在IE-11中返回false,如果您想检测IE-11,请使用以下代码:
var isIE = "ActiveXObject" in window; //window.ActiveXObject !== undefined;
如果可能的话,不要测试浏览器,而要进行特性检测。这将意味着你的代码更有可能具备未来性。比如,在这种情况下,如果你发现浏览器是IE,并因此决定使用attachEvent
,那么你会错过addEventListener
(更好)在IE9中可用的事实。
在这种情况下,测试document.addEventListener
是否存在。如果存在,你就得到了答案。
if (document.addEventListener) {
document.addEventListener(...);
} else {
document.attachEvent(...);
}
编辑:duri在上面的评论中指出,该测试在IE9(符合标准)中失败,这实际上意味着它是addEventListener
的完美测试,因为它从IE9开始可用。 然而,编写特定功能而非特定浏览器的程序仍然要好得多。
要检查浏览器是否为Internet Explorer,请使用特性检测来检查documentMode
:
http://msdn.microsoft.com/en-us/library/ie/cc196988%28v=vs.85%29.aspx
此代码用于检查浏览器是否为Internet Explorer 8、9、10或11:
var docMode = document.documentMode,
hasDocumentMode = (docMode !== undefined),
isIE8 = (docMode === 8),
isIE9 = (docMode === 9),
isIE10 = (docMode === 10),
isIE11 = (docMode === 11),
isMsEdge = window.navigator.userAgent.indexOf("Edge/") > -1;
// browser is IE
if(hasDocumentMode) {
if(isIE11){
// browser is IE11
} else if(isIE10){
// browser is IE10
} else if(isIE9){
// browser is IE9
} else if(isIE8){
// browser is IE8
}
} else {
// document.documentMode is deprecated in MS Edge
if(isMsEdge){
// browser is MS Edge
}
}
检查 document.documentMode
只能在IE8到IE11中使用,因为 documentMode
在IE8中被添加,并已在MS Edge中被弃用/删除。
http://msdn.microsoft.com/en-us/library/ff406036%28v=vs.85%29.aspx
希望这有所帮助!
更新
如果你确实需要检测IE7,请检查 document.attachEvent
:
var isIE7 = (document.attachEvent !== undefined);
if(isIE7) {
// browser is IE7
}
如果浏览器是IE7,则返回一个对象,但如果浏览器是IE11(例如),则会返回undefined
,因为IE11没有attachEvent
。
更新:
增加对MS Edge的检查。 document.documentMode
在MS Edge中已弃用。由于MS Edge的性质,您可以在用户代理中检查Edge/
。Microsoft使在MS Edge中使用功能检测变得困难。
includes()
方法在IE11及更早版本中不受支持。因此,您可以使用代码来检查includes()
方法是否受支持。这适用于所有版本的IE。但是,includes方法不适用于早期版本的Chrome、Firefox、Safari和Opera。这可能不是检测IE最有效的方法。
var aString = "something";
if(!aString.includes){
alert("You are using IE");
} else {
alert("You are not using IE");
}
false
。 - duri