JS事件
// 封装添加事件监听程序
function addEvent(ele,type,hander){
if(ele.addEvenetListener){
ele.addEventListener(type,hander,false);
} else if(ele.attachEvent){
ele.attachEvent('on'+type,hander)
}else{
ele['on'+type]=hander;
}
}
//封装删除事件监听程序
function removeEvent(ele,type,hander){
if(ele.removeEventListener){
ele.removeEventListener(type,hander,false);
}else if(ele.detachEvent){
ele.detachEvent('on'+type,hander);
}else{
ele.['on'+type]=null;
}
}
阻止特定事件的默认行为:点击链接不跳转
<body>
<a href="001.html" id="mylink">点击</a>
<script type="text/javascript">
var link=document.getElementById("mylink");
link.onclick=function(e){
if(e.preventDefault){
e.preventDefault();
}else{
e.returnValue=false;
}
}
</script>
</body>
阻止事件冒泡
<body>
<input type="button" id="btn" value="denglu">
<script>
var btn=document.getElementById("btn");
btn.onclick=function(e){
alert("hello");
if(e.stopPropagation){
e.stopPropagation();
}
else{
e.cancelBubble=true;
}
}
document.body.onclick=function(e){
alert("body is clicked");
}
</script>
</body>
如果不添加e.stopPropagation();就会在单击时弹出两个警告框。添加之后,由于阻止冒泡行为,click事件根本不会传播到document.body,因此就不会触发注册在这个元素上的 onclick事件处理程序。
跨浏览器程序
var EventUtil = {
addHandler: function(element, 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(element, type, handler){
//省略的代码
},
stopPropagation: function(event){
if (event.stopPropagation){
event.stopPropagation();
} else {
event.cancelBubble = true;
}
}
};