摘自《Javascript高级程序设计》的跨浏览器事件处理代码:
var EventUtil = {
addHandler: function(element, type, handler) {
if(element.addEventListener) { //DOM2级
element.addEventListener(type, handler, false);
} else if(element.attachEvent) { //IE/Opera
element.attachEvent('on' + type, handler);
} else { //DOM0级
element['on' + type] = handler;
}
},
removeHandler: function(element, type, handler) {
if(element.removeEventListener) {
element.removeEventListener(type, handler, false);
} else if(element.detachEvent) {
element.detachEvent('on' + type, handler);
} else {
element['on' + type] = null;
}
},
getEvent: function(event) { //获取事件对象
return event ? event : window.event; //X||IE
},
getTarget: function(event) { //获取事件目标
return event.target || event.srcElement; //X||IE
},
preventDefault: function(event) { //取消事件默认行为
if(event.preventDefault) {
event.preventDefault();
} else { //IE
event.returnValue = false;
}
},
stopPropagation: function(event) { //阻止事件冒泡
if(event.stopPropagation) {
event.stopPropagation();
} else { //IE
event.cancelBubble = true;
}
},
getRelatedTarget: function(event) { //获取相关元素(从一个元素的边界之内移到另一个元素的边界之内),仅mouseover和mouseout事件有值,其他为null
if(event.relatedTarget) {
return event.relatedTarget;
} else if(event.toElement) { //IE mouseout
return event.toElement;
} else if(event.fromElement) { //IE mouseover
return event.fromElement;
} else {
return null;
}
},
getButton: function(event) { //获取按了鼠标的哪个按钮
if(document.implementation.hasFeature('MouseEvents', '2.0')) {
return event.button;
} else {
switch(event.button) {
case 0:
case 1:
case 3:
case 5:
case 7:
return 0; //主按钮(常规设置时为左键)
case 2:
case 6:
return 2; //中间按钮
case 4:
return 1; //次按钮
}
}
},
getWheelDelta: function(event) { //获取鼠标滚轮增量值
if(event.wheelDelta) {
return event.wheelDelta; //如果是Opera9.5以前的版本则方向相反为 -event.wheelDelta
} else {
return -event.detail * 40; //Firefox 向前时为-3的倍数,向后则为3的倍数
}
},
getCharCode: function(event) { //获取键盘按键编码(keypress)
if(typeof event.charCode == 'number') {
return event.charCode;
} else {
return event.keyCode;
}
},
getClipboardText: function(event) { //获取剪贴板文本
var clipboardData = (event.clipboardData || window.clipboardData); //X:IE
return clipboardData.getData('text');
},
setClipboardText: function(event, value) { //设置剪贴板文本
if(event.clipboardData) {
return event.clipboardData.setData('text/plain', value);
} else if(window.clipboardData) { //IE
return window.clipboardData.setData('text', value);
}
}
};
例子:
var e = document.getElementById('btn');
function btnClick(){
console.log('Clicked');
}
EventUtil.addHandler(e, 'click', btnClick);
EventUtil.removeHandler(e, 'click', btnClick);
...