先来看一段实例: 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事件