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

JS点击子元素不触发父元素点击事件(js阻止冒泡)

2014-12-31 11:06 701 查看
js阻止冒泡

<html>
<title></title>
<head>
<meta charset="utf-8">
<style type="text/css">
.divone{width:100px;height:100px;background:black;position: relative;cursor: pointer}
.divchild{position: absolute;margin:10px;width:50px;height:50px;background:white;cursor: pointer}
</style>
<script type="text/javascript">
function divone(){
//这里是divone事件的代码
console.log('divone事件');
stopPropagation();
}

function divchild(){
//这里是divchild事件的代码
console.log('divchild事件');
stopPropagation();
}

function stopPropagation(e) {
e = e || window.event;
if(e.stopPropagation) { //W3C阻止冒泡方法
e.stopPropagation();
} else {
e.cancelBubble = true; //IE阻止冒泡方法
}
}
</script>
</head>
<body>

<div class="divone" onclick="divone(this)">

<div class="divchild" onclick="divchild(this)"></div>

</div>

</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: