阻止事件冒泡的方法:event的stopPropagation();的属性。
阻止事件冒泡 阻止谁身上的事件冒泡 就在谁身上调用方法
document.onclick=function (event) {
alert("文档被点击了");
}
var btn=document.getElementById('btn');
btn.onclick=function (event) {
alert("按钮被点击了");
var event=event||window.event;
event.stopPropagation();//阻止事件冒泡
};
事件冒泡的兼容封装:
btn.onclick=function (event) {
var event=event||window.event;
//阻止事件冒泡的兼容封装
if (event.stopPropagation){//正常浏览器
event.stopPropagation();
}else{
event.cancelBubble=true;//IE678
}
};
获取事件目标的方式:
var target=event.target||event.srcElement;//兼容模式
console.log(target);
console.log(target.id);