事件流描述的是從頁面中接收事件的順序。但是 IE 提出的是冒泡流,而 Netscape Communicator 提出的是捕獲流。
JavaScript 事件流
事件開始由最具體的元素(嵌套層次最深的那個節(jié)點)接收,然后逐級向上傳播為較不為具體的節(jié)點(文檔)。如下:
[js] view plaincopy
<html>
<head>
<title>事件冒泡</title>
</head>
<body>
<div id="myDiv">點擊我</div>
</body>
</html>
window.onload = function(){
var obj = document.getElementById("test");
obj.onclick = function(){
alert(this.tagName);
};
document.body.onclick = function(){
alert(this.tagName);
};
document.documentElement.onclick = function(){
alert(this.tagName);
};
document.onclick = function(){
alert("document");
};
window.onclick = function(){
alert("window");
}
};
事件傳播順序:div――>body――>html――>document
注意:
現(xiàn)代所有瀏覽器都支持冒泡事件,但實現(xiàn)還有一些差別。IE5.5 及更早版本中的事件冒泡會直接從 body 跳到 document(不執(zhí)行 html )。Firefox、Chrome 和 Safari 則將事件一直冒泡到 window 對象。
[js] view plaincopy
function getEvent(event) {
// window.event IE
// event 非IE
return event || window.event;
}
[js] view plaincopy
function stopBubble(e) {
// 如果提供了事件對象,則這是一個非IE瀏覽器
if ( e && e.stopPropagation ) {
// 因此它支持W3C的stopPropagation()方法
e.stopPropagation();
} else {
// 否則,我們需要使用IE的方式來取消事件冒泡
window.event.cancelBubble = true;
}
}
[js] view plaincopy
function stopDefault( e ) {
// 阻止默認瀏覽器動作(W3C)
if ( e && e.preventDefault ) {
e.preventDefault();
} else {
// IE中阻止函數(shù)器默認動作的方式
window.event.returnValue = false;
}
return false;
}