先來看一段實例: javascript
js: html
var $input = document.getElementsByTagName("input")[0]; var $div = document.getElementsByTagName("div")[0]; var $body = document.getElementsByTagName("body")[0]; $input.onclick = function(e){ this.style.border = "5px solid red" var e = e || window.e; alert("red") } $div.onclick = function(e){ this.style.border = "5px solid green" alert("green") } $body.onclick = function(e){ this.style.border = "5px solid yellow" alert("yellow") }
html: java
<div> <input type="button" value="測試事件冒泡" /> </div>
依次彈出」red「,」green」,」yellow」。 瀏覽器
你的本意是觸發button這個元素,卻連同父元素綁定的事件一同觸發。這就是事件冒泡。 性能
若是對input的事件綁定改成: 學習
$input.onclick = function(e){ this.style.border = "5px solid red" var e = e || window.e; alert("red") e.stopPropagation(); }
這個時候只會彈出」red「 測試
由於阻止了事件冒泡。 this
既然有事件的冒泡,也能夠有事件的捕獲,這是一個相反的過程。區別是從頂層元素到目標元素或者從目標元素到頂層元素。 spa
來看代碼: code
$input.addEventListener("click", function(){ this.style.border = "5px solid red"; alert("red") }, true) $div.addEventListener("click", function(){ this.style.border = "5px solid green"; alert("green") }, true) $body.addEventListener("click", function(){ this.style.border = "5px solid yellow"; alert("yellow") }, true)
這個時候依次彈出」yellow「,」green」,」red」。
這就是事件的捕獲。
若是把addEventListener方法的第三個參數改爲false,則表示只在冒泡的階段觸發,彈出的依次爲:」red「,」green」,」yellow」。
有一些html元素默認的行爲,好比說a標籤,點擊後有跳轉動做;form表單中的submit類型的input有一個默認提交跳轉事件;reset類型的input有重置表單行爲。
若是你想阻止這些瀏覽器默認行爲,JavaScript爲你提供了方法。
先上代碼
var $a = document.getElementsByTagName("a")[0]; $a.onclick = function(e){ alert("跳轉動做被我阻止了") e.preventDefault(); //return false;//也能夠 } <a href="http://www.nipic.com">暱圖網</a>
默認事件沒有了。
既然return false 和 e.preventDefault()都是同樣的效果,那它們有區別嗎?固然有。
僅僅是在HTML事件屬性 和 DOM0級事件處理方法中 才能經過返回 return false 的形式組織事件宿主的默認行爲。
注意:以上都是基於W3C標準,沒有考慮到IE的不一樣實現。
更多關於JavaScript事件的學習,建議你們有能夠閱讀這篇文章:編寫高性能的JavaScript事件