兼容IE与Firefox的JavaScript事件封装类

作者:交互手记

时间:2026-10-23

浏览:456

针对IE与Firefox在事件对象获取方式上的差异,本文介绍了一个自定义的JavaScript Event封装类。该类通过统一接口处理事件获取、目标识别、坐标定位及事件绑定与移除,有效解决了浏览器兼容性问题,便于在项目中复用。

文章目录

兼容IE与Firefox的JavaScript事件封装类

由于IE浏览器中event对象是全局的,而Firefox中event对象是局部的,这种差异导致直接使用不够便捷。因此,我们需要自行组装常用的事件操作,将其封装为一个类,以便于在项目中重复使用。


具体实现代码如下:

/** 
Event类定义
使用方法说明
调用Event.getEvent()可获取兼容IE和Firefox的事件对象。
调用Event.getTarget()可获取IE的srcElement或Firefox的target,即事件源。
调用Event.isIe()用于判断当前浏览器是否为IE。
调用Event.clientX()可获取IE和Firefox环境下的鼠标X坐标。
调用Event.clientY()可获取IE和Firefox环境下的鼠标Y坐标。
*/ 
var Event=new function(){
this.toString=function(){
return this.getEvent();
} 
//获取事件对象
this.getEvent=function(){
var ev=window.event;
if(!ev){
var c=this.getEvent.caller;
while(c){
ev=c.arguments[0];
if(ev && Event ==ev.constructor)
break;
c=c.caller;
} 
} 
return ev;
}; 
//获取事件源
this.getTarget=function(){
var ev=this.getEvent();
return this.isIe()?ev.srcElement:ev.target;
} 
//判断是否为IE浏览器
this.isIe=function(){
return document.all?true:false;
} 
//获取鼠标X坐标
this.clientX=function(){
var ev=this.getEvent();
var x=this.isIe()?ev.clientX:ev.pageX;
return x;
} 
//获取鼠标Y坐标
this.clientY=function(){
var ev=this.getEvent();
var y=this.isIe()?ev.clientY:ev.pageY;
return y;
} 
/**增加事件(对象,事件类型,函数指针 )
obj: html对象
sEvent: 事件名称
spNotify: 事件执行的方法
isCapture:是否允许全屏捕捉
*/ 
this.addEvent=function(obj,sEvent,fpNotify,isCapture){
sEvent=sEvent.indexOf("on")!=-1?sEvent:"on"+sEvent;
if(obj.addEventListener){
sEvent=sEvent.substring(sEvent.indexOf("on")+2);
obj.addEventListener(sEvent,fpNotify,isCapture);
}else{ //ie
if(isCapture)
obj.setCapture(isCapture);
obj.attachEvent(sEvent,fpNotify);
} 
} 
//移除事件
this.removeEvent=function(obj,sEvent,fpNotify){
if(obj.removeEventListener){
sEvent=sEvent.substring(sEvent.indexOf("on")+2)
obj.removeEventListener(sEvent,fpNotify,false);
}else{
obj.detachEvent(sEvent,fpNotify);
} 
} 
//获取鼠标按键,left=1,middle=2,right=3
this.button=function(){
var ev=this.getEvent();
if(!ev.which&&ev.button){//ie
return ev.button&1?1:(ev.button&2?3:(ev.button&4?2:0))
} 
return ev.which;
}; 
//阻止事件冒泡传递
this.stopPropagation=function(){
var ev=this.getEvent();
if(this.isIe)
ev.cancelBubble=true;
else
ev.stopPropagation();
} 
//阻止默认事件返回
this.preventDefault=function(){
var ev=this.getEvent();
if(this.isIe)
ev.returnValue=false;
else
ev.preventDefault();
} 
} 

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章