//检测是否是IE
var isIE = (navigator.userAgent.indexOf("compatible") > -1) && (navigator.userAgent.indexOf("MSIE") > -1);
//检测是否是window操作系统
var isWin = (navigator.platform == "Win32") || (navigator.platform == "Windows");
var EventUtil = new Object;
//增加事件函数
EventUtil.addEventHandler = function(oTarget,sEvetnType,fnHandler){
if(oTarget.addEventListener){
oTarget.addEventListener(sEvetnType,fnHandler,false);
}else if(oTarget.attachEvent){
oTarget.attachEvent("on"+sEvetnType,fnHandler);
}else {
oTarget["on"+sEvetnType] = fnHandler;
}
}
//删除事件函数
EventUtil.removeEventHandler = function(oTarget,sEvetnType,fnHandler) {
if(oTarget.addEventListener){
oTarget.removeEventListener(sEvetnType,fnHandler,false);
}else if(oTarget.attachEvent){
oTarget.detachEvent("on"+sEvetnType,fnHandler);
}else {
oTarget["on"+sEvetnType] = null;
}
}
//兼容IE和其他浏览器
EventUtil.formateEvent = function(oEvent){
if(isIE && isWin){
oEvent.charCode = (oEvent.type=="keypress") ? oEvent.keyCode:0;
oEvent.evetnPhase = 2;
oEvent.isChar = (oEvent.charCode > 0);
oEvent.pageX = oEvent.clientX + document.body.scrollLeft;
oEvent.pageY = oEvent.clilentY + document.body.scrollTop;
oEvent.preventDefault = function(){
this.returnValue = false;
}
if(oEvent.type=="mouseout"){
oEvent.relatedTarget = oEvent.toElement;
}else if(oEvent.type=="mouseover"){
oEvent.relatedTarget = oEvent.fromElement;
}
oEvent.stopPropagation = function(){
this.cancelBubble = true;
}
oEvent.target = oEvent.srcElement;
oEvent.timeStamp = (new Date()).getTime();
}
return oEvent;
}
EventUtil.getEvent = function(){
if(window.event){
return EventUtil.formateEvent(window.event);
}
return EventUtil.getEvent.caller.arguments[0];
}
本文详细介绍了如何使用JavaScript的EventUtil库进行事件监听,包括兼容不同浏览器和操作系统的技巧,以及事件对象的格式化处理,旨在提高用户体验并优化网页响应速度。
905

被折叠的 条评论
为什么被折叠?



