用于兼容浏览器的js写法

用于引用的源文件代码:

var Common = {
getEvent: function() {//ie/ff
if (document.all) {
return window.event;
}
func = getEvent.caller;
while (func != null) {
var arg0 = func.arguments[0];
if (arg0) {
if ((arg0.constructor == Event || arg0.constructor == MouseEvent) || (typeof (arg0) == "object" && arg0.preventDefault && arg0.stopPropagation)) {
return arg0;
}
}
func = func.caller;
}
return null;
},

getMousePos: function(ev) {//取得鼠标位置
if (!ev) {
ev = this.getEvent();
}
if (ev.pageX || ev.pageY) {
return {
x: ev.pageX,
y: ev.pageY
};
}

if (document.documentElement && document.documentElement.scrollTop) {
return {
x: ev.clientX + document.documentElement.scrollLeft - document.documentElement.clientLeft,
y: ev.clientY + document.documentElement.scrollTop - document.documentElement.clientTop
};
}
else if (document.body) {
return {
x: ev.clientX + document.body.scrollLeft - document.body.clientLeft,
y: ev.clientY + document.body.scrollTop - document.body.clientTop
};
}
},

isIE : navigator.userAgent.toUpperCase().indexOf("MSIE")?true:false,

isFirefox : navigator.userAgent.toUpperCase().indexOf("FIREFOX")?true:false,

getIeVersion: function(){//取得ie版本
var userAgent = navigator.userAgent.toLowerCase();
if(userAgent.match(/msie ([d.]+)/)!=null){//ie6--ie9
uaMatch = userAgent.match(/msie ([d.]+)/);
return uaMatch[1];
}else if(userAgent.match(/(trident)/([w.]+)/)){
uaMatch = userAgent.match(/trident/([w.]+)/);
switch (uaMatch[1]){
case "4.0":
return 8;
break;
case "5.0":
return 9;
break;
case "6.0":
return 10;
break;
case "7.0":
return 11;
break;
default:
return -1;
}
}
return -1;
},

getById: function(id) {
return "string" == typeof id ? document.getElementById(id) : id;
}
}

存储为common.js文件

下面是引用此文件的html文档

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB2312">
</head>
<body>
<input type="button" id="mousePos" value="鼠标坐标" />
<input type="button" onclick="showIeVersion();" value="IE版本" />

<script type="text/javascript" src="common.js"></script>
<script type="text/javascript">
document.getElementById("mousePos").onmousedown=function(e){
var ev = e || window.event || Common.getEvent();
var pos = Common.getMousePos(ev);
console.log('x:' + pos.x + ', y:' + pos.y);
}

function showIeVersion(){
var ieVer = parseInt(Common.getIeVersion());
if(ieVer==-1){
console.log('非IE浏览器');
}else{
console.log('IE' + ieVer);
}
}
</script>

</body>
</html>

原文地址:https://www.cnblogs.com/Logo-TPM/p/6057388.html