addEventListener和on的區別

爲何須要addEventListener?html

先來看一個片斷:函數

html代碼spa

<div id="box">追夢子</div>code

用on的代碼htm

 1 window.onload = function(){ 2 var box = document.getElementById("box"); 3 box.onclick = function(){ 4 console.log("我是box1"); 5 } 6 box.onclick = function(){ 7 box.style.fontSize = "18px"; 8 console.log("我是box2"); 9 } 10 }
     運行結果:「我是box2」

看到了吧,第二個onclick把第一個onclick給覆蓋了,雖然大部分狀況咱們用on就能夠完成咱們想要的結果,可是有時咱們又須要執行多個相同的事件,很明顯若是用on完成不了咱們想要的,那不用猜,大家確定知道了,對!addEventListener能夠屢次綁定同一個事件而且不會覆蓋上一個事件。blog

用addEventListener的代碼事件

1 window.onload = function(){ 2 var box = document.getElementById("box"); 3 box.addEventListener("click",function(){ 4 console.log("我是box1"); 5 }) 6 box.addEventListener("click",function(){ 7 console.log("我是box2"); 8 }) 9 }
    運行結果:我是box1
         我是box2

addEventListenert方法第一個參數填寫事件名,注意不須要寫on,第二個參數能夠是一個函數,第三個參數是指在冒泡階段仍是捕獲階段處理事件處理程序,若是爲true表明捕獲階段處理,若是是false表明冒泡階段處理,第三個參數能夠省略,大多數狀況也不須要用到第三個參數,不寫第三個參數默認falseget

 

第三個參數的使用io

有時候的狀況是這樣的console

<body>
  <div id="box">
    <div id="child"></div>
  </div>
</body>

若是我給box加click事件,若是我直接單擊box沒有什麼問題,可是若是我單擊的是child元素,那麼它是怎麼樣執行的?(執行順序)

1 box.addEventListener("click",function(){ 2 console.log("box"); 3 }) 4 5 child.addEventListener("click",function(){ 6 console.log("child"); 7 })
  執行的結果:
        child
        box

也就是說,默認狀況事件是按照事件冒泡的執行順序進行的。

 

若是第三個參數寫的是true,則按照事件捕獲的執行順序進行的。

1 box.addEventListener("click",function(){ 2 console.log("box"); 3 },true) 4 5 child.addEventListener("click",function(){ 6 console.log("child"); 7 })   執行的結果:         box         child

事件冒泡執行過程:

        從最具體的的元素(你單擊的那個元素)開始向上開始冒泡,拿咱們上面的案例講它的順序是:child->box

事件捕獲執行過程:

        從最不具體的元素(最外面的那個盒子)開始向裏面冒泡,拿咱們上面的案例講它的順序是:box->child

相關文章
相關標籤/搜索