您的位置:首页 > Web前端 > JavaScript

JS判断浏览器是否为IE的方式

2010-09-28 20:02 681 查看
检测浏览器版本是很多前端工作者在写跨浏览器的js程序时一项非常重要的工作,我们经常要为不同的浏览器写不同的分支代码。如今检测浏览器方式也是五花八
门,这里就记录一下各种检测方法。最后是检测方法的测试用例。

主要的测试方法分为以下几种:

1. IE中某些转义符缺失或与其他浏览器定义不同。

!+"/v1"


以下这种方法在IE9中已修复

"/v"=="v"


2. IE中数组的某些表现与其他浏览器不同

!"1"[0]


!-[1,]


[,]==","


3. IE浏览器特性,不过此类方法有些需要特别Opera的伪装做模式处理

top["execScript"]!=null


top["ActiveXObject"]!=null


!!window.attachEvent && navigator.userAgent.indexOf("Opera") === -1


!window.addEventListener&& navigator.userAgent.indexOf("Opera") === -1


!!document.all && navigator.userAgent.indexOf("Opera") === -1


4. userAgent检测,同样也需要注意Opera

/msie/i.test( navigator.userAgent ) && !/opera/i.test( navigator.userAgent )


测试用例如下:

<html>
<head>
<meta charset="UTF-8">
<title>测试IE</title>
</head>
<body>
<mce:script type="text/javascript"><!--
function dwl(s){
document.write(s);
document.write("<br/>");
}
function check(s){
var isIE = eval(s);
dwl("Test<br/>  " + s + "<br/>  " + (isIE ? "This is IE." : " is not IE."));
}
check('"//v"=="v"');				//"/v" == "v"
check('!+"//v1"');					//!+"/v1"

check('!"1"[0]');
check('top["execScript"]!=null');	//top["execScript"] != null
check('top["ActiveXObject"]!=null');//top["ActiveXObject"] != null

check('!-[1,]');					//!-[1,]
check('[,]==","');					//[,]==","

check('/msie/i.test( navigator.userAgent ) && !/opera/i.test( navigator.userAgent )');	//userAgent
check('!!window.attachEvent && navigator.userAgent.indexOf("Opera") === -1');
check('!window.addEventListener&& navigator.userAgent.indexOf("Opera") === -1');
check('!!document.all && navigator.userAgent.indexOf("Opera") === -1');

// --></mce:script>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: