JS-JQ-事件冒泡
一、冒泡的原理:
子元素會觸發父元素的事件
自上而下的觸發事件
二、解決方法:
JS:
IE:event.cancelBubble=true
FF:event.stopPropagation()
JQ:
ev.stopPropagation()
!!! - CSS
<style>
.div1{width:800px;height:500px;padding:100px;box-sizing: border-box;background:rosybrown;}
.div2{width:500px;height:200px;background:#269ABC;}
</style>
!!! - HTML
<div class="div1">
<div class="div2"></div>
</div>
!!! - JavaScript
window.onload=function()
{
var div1=document.getElementsByClassName(‘div1‘)[0];
var div2=document.getElementsByClassName(‘div2‘)[0];
div1.onclick=function()
{
alert(‘我是DIV1‘);
}
div2.onclick=function(ev)
{
var oEvent=ev||event;
if(ev.cancelBubble)
{
oEvent.cancelBubble=true;
}
else
{
oEvent.stopPropagation();
}
alert(‘我是DIV2‘);
}
}
!!! - JQuery
$(function(){
$(‘.div1‘).click(function(){
alert(‘我是DIV1‘);
});
$(‘.div2‘).click(function(ev){
alert(‘我是DIV2‘);
ev.stopPropagation();
});
})
JS-JQ-事件冒泡