談起JavaScript的 事件,事件冒泡、事件捕獲、阻止默認(rèn)事件這三個(gè)話題,無論是面試還是在平時(shí)的工作中,都很難避免。
1.事件冒泡
先來看一段代碼:
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代碼
<div> <input type="button" value="測(cè)試事件冒泡" /></div> 依次彈出”red“,"green","yellow"。
你的本意是觸發(fā)button這個(gè)元素,卻連同父元素綁定的事件一同觸發(fā)。這就是事件冒泡。
如果對(duì)input的事件綁定改為:
$input.onclick = function(e){ this.style.border = "5px solid red" var e = e || window.e; alert("red") e.stopPropagation();}這個(gè)時(shí)候只會(huì)彈出”red“,因?yàn)樽柚沽耸录芭荨?/p>
2.事件捕獲
既然有事件的冒泡,也可以有事件的捕獲,這是一個(gè)相反的過程。區(qū)別是從頂層元素到目標(biāo)元素或者從目標(biāo)元素到頂層元素。
來看一段代碼:
$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)這個(gè)時(shí)候依次彈出”yellow“,"green","red",這就是事件的捕獲。
3.阻止默認(rèn)事件
有一些html元素默認(rèn)的行為,比如說a標(biāo)簽,點(diǎn)擊后有跳轉(zhuǎn)動(dòng)作;form表單中的submit類型的input有一個(gè)默認(rèn)提交跳轉(zhuǎn)事件;reset類型的input有重置表單行為。如果你想阻止這些瀏覽器默認(rèn)行為,JavaScript為你提供了方法。
var $a = document.getElementsByTagName("a")[0];$a.onclick = function(e){ alert("跳轉(zhuǎn)動(dòng)作被我阻止了") e.preventDefault(); //return false;//也可以}<a >柯樂義</a>默認(rèn)事件沒有了。既然return false 和 e.preventDefault()都是一樣的效果,那它們有區(qū)別嗎?當(dāng)然有。
僅僅是在HTML事件屬性 和 DOM0級(jí)事件處理方法中 才能通過返回 return false 的形式組織事件宿主的默認(rèn)行為。

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注