一、冒泡的原理:
子元素会触发父元素的事件
自上而下的触发事件
二、解决方法:
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.οnlοad=function()
{
var div1=document.getElementsByClassName('div1')[0];
var div2=document.getElementsByClassName('div2')[0];
div1.οnclick=function()
{
alert('我是DIV1');
}
div2.οnclick=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();
});
})