您的位置:首页 > Web前端 > JavaScript

js基础特效04阻止事件冒泡及封装及获取事件目标

2017-04-06 17:15 260 查看
阻止事件冒泡的方法: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);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: