事件冒泡
if(window.event){
//cancelBubble的字面意思是取消冒泡
//如果事件句柄想阻止事件传播到包容对象,必须把该属性设为 true。
e.cancelBubble = true;
} else {
e.preventDefault(); //方法取消事件的默认动作
e.stopPropagation(); //stopPropagation的字面意思是停止传播。
}
//cancelBubble的字面意思是取消冒泡
//如果事件句柄想阻止事件传播到包容对象,必须把该属性设为 true。
e.cancelBubble = true;
} else {
e.preventDefault(); //方法取消事件的默认动作
e.stopPropagation(); //stopPropagation的字面意思是停止传播。
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>test-event-bubble</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
<style type="text/css">
#test-wrap div{border:1px solid #ccc;padding:5px 10px 10px;cursor:pointer;}
#test2{margin-top:15px;}
</style>
</head>
<body>
<div id="test-wrap">
<h3>事件冒泡</h3>
<div id="test">
test
<div id="sub">
sub
<div id="on">this is on</div>
</div>
</div>
<h3>没有冒泡</h3>
<div id="test2">
test2
<div id="sub2">
sub2
<div id="on2">this is on2</div>
</div>
</div>
</div>
<script type="text/javascript">
var $ = function(){ return document.getElementById(arguments[0])};
var test = $('test'),
sub = $('sub'),
on = $('on'),
test2 = $('test2'),
sub2 = $('sub2'),
on2 = $('on2');
var can = function(event){
var e = event || window.event;
if(window.event){
//cancelBubble的字面意思是取消冒泡
//如果事件句柄想阻止事件传播到包容对象,必须把该属性设为 true。
e.cancelBubble = true;
} else {
e.preventDefault(); //方法取消事件的默认动作
e.stopPropagation(); //stopPropagation的字面意思是停止传播。
}
}
on.onmouseover = function(event){
this.style.border = '2px dashed red';
}
sub.onmouseover = function(event){
this.style.border = '2px dashed green';
}
test.onmouseover = function(event){
this.style.border = '2px dashed blue';
}
on2.onmouseover = function(event){
can(event);
this.style.border = '2px dashed red';
}
sub2.onmouseover = function(event){
can(event);
this.style.border = '2px dashed green';
}
test2.onmouseover = function(event){
can(event);
this.style.border = '2px dashed blue';
}
on.onmouseout = sub.onmouseout = test.onmouseout = on2.onmouseout = sub2.onmouseout = test2.onmouseout = function(){
this.style.border = '1px solid #ccc';
}
</script>
</body>
</html>