// cancelBubble的字面意思是取消冒泡
// 如果事件句柄想阻止事件传播到包容对象,必须把该属性设为 true。
e.cancelBubble = true ;
} else {
e.preventDefault(); // 方法取消事件的默认动作
e.stopPropagation(); // stopPropagation的字面意思是停止传播。
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <title>test-event-bubble</title> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" /> <style type="text/css"> #test-wrap div{border:1px solid #ccc;padding:5px 10px 10px;cursor:pointer;} #test2{margin-top:15px;} </style> </head> <body> <div id="test-wrap"> <h3>事件冒泡</h3> <div id="test"> test <div id="sub"> sub <div id="on">this is on</div> </div> </div> <h3>没有冒泡</h3> <div id="test2"> test2 <div id="sub2"> sub2 <div id="on2">this is on2</div> </div> </div> </div> </body> </html>
运行代码