本文透過範例說明 JavaScript 中的事件捕捉(Capture)模型與事件冒泡(Bubble)模型的差異。
<html>
<head>
<script type="text/javascript">
window.onload = function(){
document.getElementById('par').addEventListener('click',function() {alert('par');},true);
document.getElementById('son').addEventListener('click',function() {alert('son');},true);
}
</script>
<style type="text/css">
#par{width:300px;height:200px;background:gray;}
#son{width:200px;height:100px;background:green;}
</style>
</head>
<body>
<div id="par">
<div id="son"></div>
</div>
</body>
</html>
<html>
<head>
<script type="text/javascript">
window.onload = function(){
document.getElementById('par').addEventListener('click',function() {alert('par');});
document.getElementById('son').addEventListener('click',function() {alert('son');});
}
</script>
<style type="text/css">
#par{width:300px;height:200px;background:gray;}
#son{width:200px;height:100px;background:green;}
</style>
</head>
<body>
<div id="par">
<div id="son"></div>
</div>
</body>
</html>
addEventListener 的第三個參數為可選參數,預設為 false,代表冒泡模型,即先觸發最內層的元素(id 為 son 的 div);若加上 true,則代表捕捉模型,會依 html → body → div 的順序觸發。
實例一點擊小 div 時,會先觸發 alert('par'),再觸發 alert('son');實例二則正好相反。
補充:若採用「物件.onclick」屬性的方式綁定事件,走的是冒泡模型。此外,IE 不支援 addEventListener,而是使用 attachEvent,但 attachEvent 不支援第三個參數,也就沒有捕捉模型。
希望本文對你的 JavaScript 程式設計有所幫助。