事件流
事件流主要分为冒泡型事件和捕获型事件。IE浏览器目前只支持冒泡型事件,而支持标准DOM的浏览器比如火狐、Chrome等两者都支持。
事件冒泡
是从下到上执行的(从小到大)。例如:点击一个按钮会把它的父级、上几级都给弹出来。
解决方法
var oEvent=ev || window.even; //兼容IE
alert("this is div1");
oEvent.cancelBubble=true;//IE
oEvent.stopPropagation();//标准
案例
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body onclick="alert('body')">
<!--html-->
<div id="div4" style="width:400px; height:400px; background:red" onclick="alert(this.style.background)">
<div id="div3" style="width:300px; height:300px; background:pink">
<div id="div2" style="width:200px; height:200px; background:yellow"
onclick="alert(this.style.background)">
<div id="div1" style="width:100px; height:100px; background:green">
<a id="aaa" href="http://www.baidu.com" onclick="return false">aaa</a>
</div>
</div>
</div>
</div>
<script>
window.onload=function(){
var oDiv1=document.getElementById("div1");
var oDiv2=document.getElementById("div2");
var oDiv3=document.getElementById("div3");
var oDiv4=document.getElementById("div4");
var oAaa=document.getElementById("aaa");
oDiv1.onclick=function(ev){
var oEven=ev || window.even;
oEven.cancelBubble=true;
oEven.stopPropagation();
alert("this is div1");
}
oDiv2.onclick=function(ev){
var oEven=ev || window.even;
oEven.cancelBubble=true;
oEven.stopPropagation();
alert("this is div2");
}
oDiv3.onclick=function(ev){
var oEven=ev || window.even;
oEven.cancelBubble=true;
oEven.stopPropagation();
alert("this is div3");
}
oDiv4.onclick=function(ev){
var oEven=ev || window.even;
oEven.cancelBubble=true;
oEven.stopPropagation();
alert("this is div4");
}
oAaa.onclick=function(ev){
var oEven=ev || window.even;
oEven.cancelBubble=true;
oEven.stopPropagation();
alert("this is a");
return false;//组织跳转
}
}
</script>
</body>
</html>