事件在不同浏览器需要兼容性处理,现封装起来,便于日后使用和学习。
var EventUtil = {
//添加事件处理
addHandler: function(element, type, handler) {
if(element.addEventListener) {
element.addEventListener(type, handler, false);
}else if(element.attachEvent) {
element.attachEvent("on" + type, handler);
}else{
element["on" + type] = handler;
}
},
//获得事件对象
getEvent: function(event) {
return event? event : window.event;
},
//获取事件目标
getTarget: function(event) {
return event.target || event.srcElement;
},
//取消事件默认行为
preventDefault: function(event) {
if(event.preventDefault()) {
event.preventDefault();
}else{
event.returnValue = false;
}
},
//移除事件
removeHandler: function() {
if(element.removeEventListener) {
element.removeEventListener(type, handler, false);
}else if(element.detachEvent){
element.detachEvent("on" + type, handler);
}else{
element["on" + type] = null;
}
},
//阻止事件冒泡
stopPropagation: function(event) {
if(event.stopPropagation) {
event.stopPropagation();
}else{
event.canceBubble = true;
}
},
//获取相关元素,一般是mouseover,mouseout,focus等
getRelatedTarget: function(event) {
if(event.relatedTarget) {
return event.relatedTarget;
}else if(event.toElement) {
return event.toElement;
}else if(event.fromElement) {
return event.fromElement;
}else{
return null;
}
},
//获取按键码
getCharCode: function(event) {
return (typeof event.charCode == 'number' ? event.charCode : event.keyCode);
},
//获取剪切板数据
getClipboardText: function(event) {
var getClipboardData = window.clipboardData || event.clipboardData;
return clipboardData.getData("text");
}
}