js之事件冒泡和事件捕获

来源:互联网 发布:淘宝代销怎么上架宝贝 编辑:程序博客网 时间:2024/04/30 10:55

事件冒泡(的过程):事件从发生的目标(event.srcElement||event.target)开始,沿着文档逐层向上冒泡,到document为止。
事件捕获(的过程):则是从document开始,沿着文档树向下,直到事件目标为止。

关键一句:在IE浏览器中,只发生事件冒泡的过程;在W3C(或支持事件捕获的)浏览器中,先发生捕获的过程,再发生冒泡的过程。

想要添加一个由捕获过程触发的事件,只能这样了:
addEventListener('click',functionname,true);//该方法在IE下报错(对象不支持此属性或方法)

注:将第三个参数设置为true,表明该事件是为捕获过程设置的。如果第三个参数为false,则等同onclick =functionname;

<script type="text/javascript">function $(id){    return document.getElementById(id);}function altin(){    alert("in");}function altmiddle(){    alert("middle");}function altout(){    alert("out")}window.onload=function() {    $('o').onclick = altout;    //$('m').onclick = altmiddle;    $('m').addEventListener('click',altmiddle,true);    $('i').onclick = altin;}</script></head><body><div id="o" style="width:400px;height:400px;border:1px solid #CCCCCC;">    <div id="m" style="width:200px;height:200px;border:1px solid #CCCCCC;">        <div id="i" style="width:100px;height:100px;border:1px solid #CCCCCC;">        </div>    </div></div></body></html>

以上代码执行效果如下:

1、$('m').onclick = altmiddle;

a)当点击#i时,显示顺序为in,middle,out

b)当点击#m时,显示顺序为middle,out

c)当点击#o时,显示顺序为out

2、$('m').addEventListener('click',altmiddle,true);

a)当点击#i时,显示顺序为middle,in,out

b)当点击#m时,显示顺序为middle,out

c)当点击#o时,显示顺序为out

3、$('m').addEventListener('click',altmiddle,false);

a)当点击#i时,显示顺序为in,middle,out

b)当点击#m时,显示顺序为middle,out

c)当点击#o时,显示顺序为out

 

把事件捕获和冒泡的过程统称为事件的传播
事件的传播是可以阻止的:
• 在W3C中,使用stopPropagation()方法
• 在IE下设置cancelBubble = true;

在捕获的过程中stopPropagation()后,后面的冒泡过程也不会发生了~

阻止事件的默认行为,例如click <a>后的跳转~
• 在W3C中,使用preventDefault()方法;
• 在IE下设置window.event.returnValue = false;

注:不是所有的事件都能冒泡,例如:blur、focus、load、unload,(这个是从别人的文章里摘过来的,我没测试)。