<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title> Document </title></head>
<body>
<a href=‘#‘ id=‘btn‘>button</a>
</body>
</html>
<script>
var EventUtil = {
//添加事件
addHandler:function(element, type, handler){
if(element.addEventListener){
element.addEventListener(type, handler, false); //标准
}else if(element.attachEvent){
element.attachEvent(‘on‘+type, handler); //IE
}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;
}
},
//阻止冒泡
stopPropagation:function(event){
if(event.stopPropagation){
event.stopPropagation();
}else{
event.cancelBubble = true;
}
},
//移除绑定
removeHandler:function(element, type, handler){
if(element.removeEventListener){
element.removeEventListener(type, handler, false); //标准
}else if(element.detachEvent){
element.detachEvent(‘on‘+type, handler); //IE
}else{
element[‘on‘+type] = null;
}
}
}function fn(){
var e = EventUtil.getEvent();
//alert(EventUtil.getTarget(e));
//EventUtil.stopPropagation(e);
EventUtil.preventDefault(e);
}EventUtil.addHandler(document.getElementById(‘btn‘), ‘click‘, fn);
//EventUtil.removeHandler(document.getElementById(‘btn‘), ‘click‘, fn);document.onclick = function(){
alert(123);
}
</script>
跨浏览器的事件处理程序