今天学了js的事件冒泡,在网上看到许多事件捕获和冒泡的文章,下面是自己的一些总结:
事件捕获:事件捕获是从document开始从外到内查找事件触发的目标元素;
事件冒泡:从目标元素开始到document一层一层向上冒,中间遇到同类事件也会执行。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style type="text/css">
#one{width: 400px;height: 400px;background-color: #7fdefb;font-size: 28px;}
#two{width: 300px;height: 300px;background-color: #30cdfd;font-size: 28px;}
#three{width: 200px;height: 200px;background-color: #00c2fd;font-size: 28px;}
</style>
</head>
<body>
<div id="one" οnclick="alert(1);">one
<div id="two" οnclick="alert(2);">two
<div id="three" οnclick="alert(3);">three
</div>
</div>
</div>
</body>
</html>
如上,3个div嵌套,当点击最内层的three,接着会继续执行two,然后到one。这就是事件冒泡。
W3C中定义了一个事件监听的方法element.addEventListener(type, listener,useCapture);支持除IE6~8的浏览器,如我要给上面的div#three添加事件,可以这样写:
three.addEventListener(’click‘,function(){alert(3);},false);这就是一般情况下的冒泡执行事件,第一个元素是事件类型不用加on,第二个是执行的函数,第三个是是否
用捕获执行事件。当为true时,事件会从外到内捕获事件时先执行,如把上面的onclick事件换成如下代码:
window.οnlοad=function (){
var one=document.getElementById('one');
var two=document.getElementById('two');
var three=document.getElementById('three');
// 最内层的盒子采用捕获执行事件,上面的three
three.addEventListener('click',function (){
alert('three');
},true);
// 中间盒子也采用捕获执行事件,上面的two
two.addEventListener('click',function (){
alert('two');
},true);
// 外层的盒子采用冒泡执行事件
one.addEventListener('click',function (){
alert('one');
},false);
};
当你点击最内层的three盒子时,首先执行的是two的事件,然后再执行three的事件,最后执行one的事件。因为one和two盒子都是捕获执行事件,从外到内顺序执行。
不过一般不这样用,按照默认的冒泡执行事件即可,在IE中也定义了element.attachEvent('on'+type,listener)添加事件,默认冒泡执行事件,IE11已经弃用这个方法了。
在实际项目中,我们一般要阻止事件冒泡。IE中使用cancelBubble,FF中使用stopPropation()。如
<pre name="code" class="javascript">window.οnlοad=function (){
var one=document.getElementById('one');
var two=document.getElementById('two');
var three=document.getElementById('three');
three.οnclick=function (ev){
// event兼容性处理
var iEvent=ev||event;
alert('three');
iEvent.cancelBubble=true;
};
two.οnclick=function (ev){
var iEvent=ev||event;
alert('two');
iEvent.cancelBubble=true;
};
one.οnclick=function (){
alert('one');
}
};
如上加了阻止事件冒泡,点击three就不会执行外层的two和one了,cancelBubble经测试在ff、Chrome等可以用,stopPropation()在IE6~10都不可以用。