首页 > 编程语言 > 详细

JavaScript中的事件冒泡定义及取消

时间:2016-01-07 00:56:09      阅读:145      评论:0      收藏:0      [点我收藏+]
  • 事件冒泡:如果元素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>

JavaScript中的事件冒泡定义及取消

原文:http://www.cnblogs.com/clcloveHuahua/p/5107845.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!