標籤:
冒泡事件可以查詢上個隨筆,
捕捉事件正好和冒泡時間正反著
所以這代碼我把冒泡事件注釋,
html和css的內容
<style type="text/css"> #box1{width:500px;height:500px;background:#900;} #box2{width:400px;height:400px;background:#090;} #box3{width:300px;height:300px;background:#009;} #box4{width:200px;height:200px;background:#990;} #box5{width:100px;height:100px;background:#099;}</style><body><div id="box1"> <div id="box2"> <div id="box3"> <div id="box4"> <div id="box5"> </div> </div> </div> </div></div>
js部分代碼
1 <script> 2 window.onload=function() 3 { 4 //監聽事件 5 var $=function(_id){return document.getElementById(_id);} 6 document.addEventListener("click", function(){alert("捕抓中,你點擊了document")}, true); 7 document.body.addEventListener("click", function(){alert("捕抓中,你點擊了body")}, true); 8 $("box1").addEventListener("click", function(){alert("捕抓中,你點擊了id為:"+this.id +"的div")}, true); 9 $("box2").addEventListener("click", function(){alert("捕抓中,你點擊了id為:"+this.id +"的div")}, true);10 $("box3").addEventListener("click", function(){alert("捕抓中,你點擊了id為:"+this.id +"的div")}, true);11 $("box4").addEventListener("click", function(){alert("捕抓中,你點擊了id為:"+this.id +"的div")}, true);12 // $("box5").addEventListener("click", function(){alert("捕抓中,你點擊了id為:"+this.id +"的div")}, true);13 14 15 //冒泡事件16 // var $=function(_id){return document.getElementById(_id);}17 // document.addEventListener("click", function(){alert("冒泡中,你點擊了document")}, false);18 // document.body.addEventListener("click", function(){alert("冒泡中,你點擊了body")}, false);19 // $("box1").addEventListener("click", function(){alert("冒泡中,你點擊了id為:"+this.id +"的div")}, false);20 // $("box2").addEventListener("click", function(){alert("冒泡中,你點擊了id為:"+this.id +"的div")}, false);21 // $("box3").addEventListener("click", function(){alert("冒泡中,你點擊了id為:"+this.id +"的div")}, false);22 // $("box4").addEventListener("click", function(){alert("冒泡中,你點擊了id為:"+this.id +"的div")}, false);23 // // $("box5").addEventListener("click", function(){alert("冒泡中,你點擊了id為:"+this.id +"的div")}, false);24 25 26 //刪除監聽事件,必須完全一樣27 var del =function(){alert("冒泡中,你點擊了id為: "+this.id +"的div")}28 $("box5").addEventListener("click", del, false);29 // $("box5").removeEventListener("click",del, false);30 31 32 33 //ie用的是attachEvent() 和detachEvent() 都有兩個參數 ie11也不支援了34 // $("box5").attachEvent("onclick",del);35 // $("box5").detachEvent("onclick",del);36 37 38 }39 </script>
其實捕捉監聽事件和冒泡事件只是函數的一個參數不同,一個true,一個false。
其實主要有時候我們實現某些功能時,需要移除捕捉和冒泡事件。
js的捕捉事件,冒泡事件