DIV CSS 佈局教程網

JavaScript 事件捕捉模型與冒泡模型實解
編輯:關於JavaScript     

本文透過範例說明 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 程式設計有所幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved