阻止事件冒泡(stopPropagation和cancelBubble)和阻止默认行为(preventDefault和returnValue)

时间:2024-05-01 08:36:27
<div id="divId1" style="width:500px;height:500px;background-color:#3ac;text-align:center;" align="center">
<div id="divId2" style="width:400px;height:400px;background-color:#f1f; margin:0 auto;">开始啦</div>
</div> document.getElementById('divId1').onclick = function(){
alert('divId1');
}
var eleDiv2 = document.getElementById('divId2');
if(eleDiv2.addEventListener){
eleDiv2.addEventListener('click',function(evt){
alert('divId2');
evt.stopPropagation();
},false);
}else{
eleDiv2.attachEvent('onclick',function(evt){
alert('divId2');
evt.cancelBubble = true;
});
}
    //阻止冒泡事件
function stopBubble(e) {
if (e && e.stopPropagation) {//非IE
e.stopPropagation();
}
else {//IE
window.event.cancelBubble = true;
}
} function stopDefault(e) {
//阻止默认浏览器动作(W3C)
if (e && e.preventDefault)
e.preventDefault();
//IE中阻止函数器默认动作的方式
else
window.event.returnValue = false;
return false;
}