工作中偶尔会遇到Javascript冒泡的问题,阻止冒泡的方法:
W3C:stopPropagation()
IE:window.event.cancelBubble = true
运行以下代码,然后注释掉”//阻止冒泡”后面那段代码,看看发生的变化。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 0 Transitional//EN" "http://www.worg/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.worg/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
div {
padding:10px;
border:1px solid #CCC;
}
#d1 {
width:400px;
}
#msg {
border-color:#CCC;
padding:3px;
margin-bottom:10px;
}
</style>
<script>
var isIE = /*@cc_on!@*/!1;
window.onload = m;
function m(){
for (var i=1; i<6; i++){
document.getElementById('d'+i).onmouseover = changeStyle;
document.getElementById('d'+i).onmouseout = changeStyle;
}
}
function changeStyle(e){
e = e || window.event;
var msg = document.getElementById('msg');
if (e.type == 'mouseover'){
this.style.borderColor = '#FF0000';
msg.innerHTML = '你当前鼠标经过的DIV ID:' + this.id;
}else if(e.type == 'mouseout'){
this.style.borderColor = '#CCCCCC';
msg.innerHTML = '鼠标状态';
}
//阻止冒泡
if (isIE){
e.cancelBubble = true;
}else{
e.stopPropagation();
}
}
</script>
</head>
<body>
<div id="msg">鼠标状态</div>
<div id="d1">ID:d1
<div id="d2">ID:d2
<div id="d3">ID:d3
<div id="d4">ID:d4
<div id="d5">ID:d5 </div>
</div>
</div>
</div>
</div>
</body>
</html>








