首页 > 技术文章 > JavaScript中的事件冒泡定义及取消

clcloveHuahua 2016-01-06 23:19 原文

  • 事件冒泡:如果元素A嵌套在元素B中,那么A被点击不仅A的onclick事件会被触发,B的onclick也会被触发。触发的顺序是“由内而外” 。

    验证:在页面上添加一个div、p、strong,在div、p、strong中添加onclick事件响应

  • 取消事件冒泡: window.event.cancelBubble = true;//IE下的写法。  

          arguments[0].stopPropagation();//火狐中的写法。

 

例子:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<style type="text/css">
div {
height: 400px;
width: 600px;
background-color: green;
/*当鼠标移到标签的位置时,显示成手*/
cursor: pointer;
}

p {
height: 200px;
width: 300px;
background-color: pink;
cursor: pointer;
}

strong {
cursor: pointer;
}
</style>
<script type="text/javascript">
//给div、p、strong标签分别注册一个点击事件。
//只能写在一个onload中,如果有3个onload事件只会执行最后一个onload事件。
onload = function () {
document.getElementById('dv').onclick = function () {
alert(this.id);
};
document.getElementById('p').onclick = function () {
alert(this.id);

if (arguments.length > 0) {
//火狐中取消冒泡事件
arguments[0].stopPropagation();
} else {
//IE中的取消冒泡事件
window.event.cancelBubble = true;
}
window.event.cancelBubble = true;
};
document.getElementById('st').onclick = function () {
alert(this.id);
if (arguments.length > 0) {
//火狐中取消冒泡事件
arguments[0].stopPropagation();
} else {
//IE中的取消冒泡事件
window.event.cancelBubble = true;
}
};

};
</script>
</head>
<body>
<div id="dv">
<p id="p">
<strong id="st">这是一个div标签下的p标签下的strong标签</strong>
</p>
</div>
</body>
</html>

推荐阅读