js 点击事件 阻止冒泡
程序员文章站
2022-05-13 16:02:19
...
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>阻止冒泡</title>
<meta name="keywords" content="阻止冒泡" />
<meta name="description" content="阻止冒泡" />
</head>
<body>
<div onclick="parentClick(this);">
<div onclick="childClick(this);"></div>
</div>
<script>
function parentClick(obj){
alert('父级元素点击事件');
}
function childClick(){
// 阻止冒泡:点击子级时,不触发父级元素的点击事件
var e = getEvent();
if (window.event) {
e.cancelBubble = true;
}else if(e.preventDefault){
e.stopPropagation();//阻止冒泡
}
alert('子级元素点击事件');
}
//获取event(兼容火狐)
function getEvent(){
if(window.event){return window.event;}
var func = getEvent.caller;
while(func != null){
var arg0 = func.arguments[0];
if(arg0){
if((arg0.constructor == Event || arg0.constructor == MouseEvent
|| arg0.constructor == KeyboardEvent)
|| (typeof(arg0) == "object" && arg0.preventDefault
&& arg0.stopPropagation)){
return arg0;
}
}
func = func.caller;
}
return null;
}
</script>
</body>
</html>