Code
JavaScript程式碼
//如果提供了事件對象,則這是一個非IE瀏覽器
if ( e && e.stopPropagation )
//因此它支援W3C的stopPropagation()方法
e.stopPropagation();
else
//否則,我們需要使用IE的方式來取消事件冒泡
window.event.cancelBubble = true;
return false;
2.阻止瀏覽器的預設行為
JavaScript程式碼
//如果提供了事件對象,則這是一個非IE瀏覽器
if ( e && e.preventDefault )
//阻止預設瀏覽器動作(W3C)
e.preventDefault();
else
//IE中阻止函數器預設動作的方式
window.event.returnValue = false;
return false;
Code
1<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
2<html xmlns=" http://www.w3.org/1999/xhtml " lang="gb2312">
3<head>
4<title> 阻止JavaScript事件冒泡傳遞(cancelBubble 、stopPropagation)</title>
5<meta name="keywords" content="JavaScript,事件冒泡,cancelBubble,stopPropagation" />
6<script type="text/javascript">
7function doSomething (obj,evt) {
8alert(obj.id);
9var e=(evt)?evt:window.event;
10if (window.event) {
11e.cancelBubble=true;
12} else {
13//e.preventDefault();
14e.stopPropagation();
15}
16}
17</script>
18</head>
19<body>
20<div id="parent1" onclick="alert(this.id)" style="width:250px;background-color:yellow">
21<p>This is parent1 div.</p>
22<div id="child1" onclick="alert(this.id)" style="width:200px;background-color:orange">
23<p>This is child1.</p>
24</div>
25<p>This is parent1 div.</p>
26</div>
27<br />
28<div id="parent2" onclick="alert(this.id)" style="width:250px;background-color:cyan;">
29<p>This is parent2 div.</p>
30<div id="child2" onclick="doSomething(this,event);" style="width:200px;background-color:lightblue;">
31<p>This is child2. Will bubble.</p>
32</div>
33<p>This is parent2 div.</p>
34</div>
35</body>
36</html>