标签:
<html>
<title>事件</title>
<meta charset="utf-8"/>
<body>
<div id="box">
<input type="button" value="按钮" id="btn" onclick="showMes()"/>
<input type="button" value="按钮2" id="btn2"/>
<input type="button" value="按钮3" id="btn3"/>
<a href="event.html" id="go" target="_blank">跳转</a>
</div>
</body>
</html>
<script>
/**
* 非IE
* event.type 获取事件的类型
* event.target属性 获取事件的目标
* event.stopPropagation()方法;//阻止事件冒泡
* event.preventDefault()方法;//阻止事件默认行为
*
* IE
* event.type 获取事件的类型
* event.srcElement
* event.cancelBubble属性阻止事件冒泡
* 设置为true为阻止冒泡,设置为false不阻止冒泡
* returnValue=false 阻止事件默认行为
*
*/
function showMes(event){
event = event || window.event;
var ele = event.target || event.srcElement;
alert(ele.nodeName);
}
function showbox(){
alert(‘这里放盒子‘);
}
function stopGoto(event){
//event.type 获取事件的类型
//event.target属性 获取事件的目标
event.stopPropagation();//阻止事件冒泡
event.preventDefault();//阻止事件默认行为
}
var btn2 = document.getElementById("btn2");
var btn3 = document.getElementById("btn3");
var go = document.getElementById("go");
btn2.onclick = function(){
alert(‘通过DOM0级添加事件‘);
}
btn2.onclick = null;
//DOM2级事件
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;
}
},
//删除句柄
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;
},
getElement: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;
}
}
};
eventUtil.addHandler(btn3,"click",showMes);
//eventUtil.removeHandler(btn3,"click",showMes);
eventUtil.addHandler(box,"click",showbox);
eventUtil.addHandler(go,"click",stopGoto);
</script>
javascript DOM事件总结
标签:
原文地址:http://www.cnblogs.com/gide/p/4564074.html