之前一直使用检查navigator.userAgent字符串来判断浏览器类型
switch(navigator.userAgent.toLowerCase().indexOf("msie"))//firefox|opera|safari|msie
{
case(-1):
alert("DOM浏览器");
default:
alert("IE浏览器");
}
f
今天在看一篇文章中提到用户在某些浏览器可以更改userAgent,这样就不能单纯使用这个方法来检查浏览器。在实际使用中一般检查最多的是ie浏览器与标准dom浏览器的区别,这样可以使用window.addEventListener来判断这两种类型的浏览器
if(typeof window.addEventListener==="function"){
alert("DOM浏览器");
}else{
alert("IE");
}
高手写的一个检测浏览器的代码
var isIE = !!(window.attachEvent && !window.opera);
var isOpera = !!window.opera;
var isSafari = navigator.userAgent.indexOf(’AppleWebKit/’) > -1;
var isMoz = navigator.userAgent.indexOf(’Gecko’) > -1 && navigator.userAgent.indexOf(’KHTML’) == -1;
var isMobileSafari = !!navigator.userAgent.match(/Apple.*Mobile.*Safari/);
var isIE5 = (navigator.appVersion.indexOf("MSIE 5")>0) || (navigator.appVersion.indexOf("MSIE")>0 && parseInt(navigator.appVersion)> 4);
var isIE55 = (navigator.appVersion.indexOf("MSIE 5.5")>0);
var isIE6 = (navigator.appVersion.indexOf("MSIE 6")>0);
var isIE7 = (navigator.appVersion.indexOf("MSIE 7")>0);
var isIE8 = (navigator.appVersion.indexOf("MSIE 8")>0);
attachEvent方法,为某一事件附加其它的处理事件。(不支持Mozilla系列)
addEventListener方法 用于 Mozilla系列
举例:
document.getElementById("btn").onclick = method1;
document.getElementById("btn").onclick = method2;
document.getElementById("btn").onclick = method3;
如果这样写,那么将会只有medhot3被执行
写成这样:
var btn1Obj = document.getElementById("btn1");
//object.attachEvent(event,function);
btn1Obj.attachEvent("onclick",method1);
btn1Obj.attachEvent("onclick",method2);
btn1Obj.attachEvent("onclick",method3);
执行顺序为method3->method2->method1
如果是Mozilla系列,并不支持该方法,需要用到addEventListener
var btn1Obj = document.getElementById("btn1");
//element.addEventListener(type,listener,useCapture);
btn1Obj.addEventListener("click",method1,false);
btn1Obj.addEventListener("click",method2,false);
btn1Obj.addEventListener("click",method3,false);
执行顺序为method1->method2->method3
使用实例:
1。
var el = EDITFORM_DOCUMENT.body;
//先取得对象,EDITFORM_DOCUMENT实为一个iframe
if (el.addEventListener)...{
el.addEventListener('click', KindDisableMenu, false);
} else if (el.attachEvent)...{
el.attachEvent('onclick', KindDisableMenu);
}
2。
if (window.addEventListener) ...{
window.addEventListener('load', _uCO, false);
} else if (window.attachEvent) ...{
window.attachEvent('onload', _uCO);
}