<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#box1{
width: 200px;
height: 200px;
background-color: #CCBBDD;
}
span{
background-color: yellow;
}
</style>
<script type="text/javascript">
window.onload = function(){
/*
* 事件的冒泡(bubble)
* - 所谓的冒泡指的就是事件的向上传导,当后代元素上的事件被触发,其祖先上的元素也会同时触发
* - 在开发中大部分情况都是有用的,如果不希望发生事件冒泡可以通过事件对象来取消冒泡
*/
//为span绑定一个单击响应函数
var span01 = document.getElementsByTagName("span");
span01[0].onclick = function(event){
event = event || window.event;
alert("我是span的单击响应函数");
//取消冒泡
//可以将事件对象的cancelBubble设置为true,即可取消冒泡
event.cancelBubble = true;
};
//为span绑定一个单击响应函数
var box01 = document.getElementById("box1");
box01.onclick = function(){
event = event || window.event;
alert("我是div的单击响应函数");
event.cancelBubble = true;
};
document.onclick = function(){
alert("我是body的单击响应函数");
};
};
</script>
</head>
<body>
<div id="box1">
我是box1
<span>
我是span
</span>
</div>
</body>
</html>
浏览器中的输出效果