// cancelBubble在IE下有效
// stopPropagation在Firefox下有效
stopPropagation
不再派发事件。
终止事件在传播过程的捕获、目标处理或起泡阶段进一步传播。调用该方法后,该节点上处理该事件的处理程序将被调用,事件不再被分派到其他节点。
cancelable 事件返回一个布尔值。如果用 preventDefault() 方法可以取消与事件关联的默认动作,则为 true,否则为 fasle。
一个小例子
<!DOCTYPE html>
<head>
<title> 阻止JavaScript事件冒泡传递(cancelBubble 、stopPropagation)</title>
<meta name="keywords" content="JavaScript,事件冒泡,cancelBubble,stopPropagation" />
<script type="text/javascript">
// cancelBubble在IE下有效
// stopPropagation在Firefox下有效
function doSomething (obj,evt) {
alert(obj.id);
var e=(evt)?evt:window.event;
if (window.event) {
e.cancelBubble=true;
} else {
//e.preventDefault();
e.stopPropagation();
}
}
</script>
</head>
<body>
<div id="parent1" onclick="alert(this.id)" style="margin-bottom 20px;width:250px;background-color:yellow">
<p>This is parent1 div.</p>
<div id="child1" onclick="alert(this.id)" style="margin-bottom 20px;width:200px;background-color:orange">
<p>This is child1.</p>
</div>
<p>This is parent1 div.</p>
</div>
<br />
<div id="parent2" onclick="alert(this.id)" style="margin-bottom 20px;width:250px;background-color:cyan;">
<p>This is parent2 div.</p>
<div id="child2" onclick="doSomething(this,event);" style="margin-bottom 20px;width:200px;background-color:lightblue;">
<p>This is child2. Will bubble.</p>
</div>
<p>This is parent2 div.</p>
</div>
</body>
</html>
<head>
<title> 阻止JavaScript事件冒泡传递(cancelBubble 、stopPropagation)</title>
<meta name="keywords" content="JavaScript,事件冒泡,cancelBubble,stopPropagation" />
<script type="text/javascript">
// cancelBubble在IE下有效
// stopPropagation在Firefox下有效
function doSomething (obj,evt) {
alert(obj.id);
var e=(evt)?evt:window.event;
if (window.event) {
e.cancelBubble=true;
} else {
//e.preventDefault();
e.stopPropagation();
}
}
</script>
</head>
<body>
<div id="parent1" onclick="alert(this.id)" style="margin-bottom 20px;width:250px;background-color:yellow">
<p>This is parent1 div.</p>
<div id="child1" onclick="alert(this.id)" style="margin-bottom 20px;width:200px;background-color:orange">
<p>This is child1.</p>
</div>
<p>This is parent1 div.</p>
</div>
<br />
<div id="parent2" onclick="alert(this.id)" style="margin-bottom 20px;width:250px;background-color:cyan;">
<p>This is parent2 div.</p>
<div id="child2" onclick="doSomething(this,event);" style="margin-bottom 20px;width:200px;background-color:lightblue;">
<p>This is child2. Will bubble.</p>
</div>
<p>This is parent2 div.</p>
</div>
</body>
</html>