什么是事件冒泡?
先上代码看,思考以下代码的执行结果~~
<div id="box1">
<div id="box2"></div>
</div>
var obox2=document.getElementById('box2');
var obox1=document.getElementById("box1");
obox2.addEventListener('touchstart', touchStartBox2,false);
obox2.onclick=function(e){
console.log("children default");
}
obox1.addEventListener('touchstart', touchStartBox1,false);
obox1.onclick=function(){
console.log("parent default");
}
function touchStartBox2(e){
console.log("children bubble");
}
function touchStartBox1(e){
console.log("parent bubble");
}
以上代码中,box2和box1都有touch事件和click事件。触发box2的touch事件,box1的touch事件也会执行。这个叫 事件冒泡
什么是默认事件?
还是以上代码,触发touch事件300ms后会触发click事件,这是一个默认事件
有了以上两个概念,重新思考以上代码的执行结果。看看和你想的一样不?
运行结果 :
children bubble //先执行box2的touch事件
parent bubble //然后执行box1的touch事件
children default //300ms后执行box2的默认事件click
parent default 300ms后执行box1的默认事件click
现在,应该大致有一个冒泡和默认事件的概念了吧,冒泡,顾名思义,一级一级element元素往上走,默认事件,一个element上的不同事件。
那么,阻止冒泡可以阻止默认事件吗?
先看代码及结果然后进行分析:
function touchStartBox2(e){
e.stopPropagation(); //阻止box2的touch事件的冒泡
console.log("children bubble");
}
结果如下:
children bubble //box2触发touch事件
children default // box2触发click事件
parent default // box1触发click事件
想一下,阻止冒泡的话,box2 的 touch 事件不会冒泡到 box1 的 touch 事件,那么:
box2 的 touch事件会触发后
(1) box1 的 touch不会触发 (因为box2的 touch阻止冒泡了,注意注意注意:click事件没有阻止冒泡)
(2) box2的 click 触发说了冒泡是一级一级的影响不同的element,那么不会影响 box2 的 click (因为这个click是touch 触发300ms后会默认触发的,还在box2上面)
(3) box1 触发click事件,因为 box2 触发了click事件,box2的click事件没有阻止冒泡,因此box2的click冒泡到了 box1 的 click(此时,box2 的click是默认事件,box1的click事件是冒泡事件)
结论:阻止冒泡没有阻止默认事件。且在哪个事件里面添加阻止冒泡,阻止的只是该事件的冒泡!
阻止默认事件可以阻止冒泡吗?
还是先看例子~~
function touchStartBox2(e){
e.preventDefault();//阻止默认事件
console.log("children bubble");
}
运行结果:
children bubble
parent bubble
分析:
box2 阻止默认事件后
(1) box2 的click不执行(被阻止)
(2) box1的touch事件执行(没有阻止冒泡)
(3) box1的click不执行(阻止默认事件所有元素的默认事件都会被阻止)
结论:阻止默认事件不会阻止冒泡
总结而言:阻止冒泡和阻止默认行为没啥关系,阻止冒泡只阻止当前事件的冒泡,不会阻止其他事件冒泡,也不会阻止默认事件。阻止默认事件同样不会阻止冒泡,但是会把默认事件都阻止掉。