JS阻止冒泡事件
JS事件流中有一種事件被稱為“冒泡事件”,當一個元素被觸發一個事件時,該目標元素上的事件會優先被執 行,然後向外傳播到每個祖先元素,恰如水裡的一個泡泡似的,從產生就一直往上冒,到達水平面時,它才消失。在這個過程中,如果你只希望觸發目標元素上的事 件,而不想它傳播到祖先元素上去,那麼你需要在“泡泡”離開物件之前刺破它。下面,就以一個簡單的Demo來演示下JS如何阻止事件冒泡:
<!DOCTYPEhtmlPUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html; charset=UTF-8">
<title>js阻止事件冒泡的DEMO</title>
<scripttype="text/javascript">
//阻止冒泡的方法
function stopPP(e)
{
var evt = e|| window.event;
//IE用cancelBubble=true來阻止而FF下需要用stopPropagation方法
evt.stopPropagation ?evt.stopPropagation() : (evt.cancelBubble=true
}
</script>
</head>
<body>
<divstyle="margin: 150px 400px;width: 700px; height: 550px;background-color: #878788;"onclick="alert('最外層div上的onclick事件');">
<h2>最外層div上的onclick事件</h2>
<divstyle="margin: 100px; width: 500px; height: 300px;background-color: #545444;"
<h3>中間層div上的onclick事件</h3>
<divstyle="margin: 60px 100px; height: 100px; width: 300px;background-color: red;"onclick="stopPP(arguments[0]);alert('最內層div上的onclick事件');">
<h4>最內層div上的onclick事件”</h4>
</div>
</div>
</div>
</body>
</html>