先來看一段實例:
js:
var $input = document.getElementsByTagName("input")[0]; var $p = document.getElementsByTagName("p")[0]; var $body = document.getElementsByTagName("body")[0]; $input.onclick = function(e){ this.style.border = "5px solid red" var e = e || window.e; alert("red") } $p.onclick = function(e){ this.style.border = "5px solid green" alert("green") } $body.onclick = function(e){ this.style.border = "5px solid yellow" alert("yellow") }
html:
<p> <input type="button" value="測試事件冒泡" /> </p>
依次彈出”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“
因為阻止了事件冒泡。
既然有事件的冒泡,也可以有事件的捕獲,這是一個相反的過程。區別是從頂層元素到目標元素或者從目標元素到頂層元素。
來看代碼:
$input.addEventListener("click", function(){ this.style.border = "5px solid red"; alert("red") }, true) $p.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的不同實現。
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com