电脑技术学习

阻止JavaScript事件冒泡传递

dn001

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>