Tag Archives: 事件冒泡

阻止Javascript事件冒泡

工作中偶尔会遇到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;
}
[...]