事件冒泡
2017-04-20 本文已影响0人
洛洛kkkkkk
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
.mingye{
width: 600px;
height: 600px;
background-color: yellow;
}
.mingba{
width: 400px;
height: 400px;
background-color: blue;
}
.ming{
width: 200px;
height: 200px;
background-color: red;
}
</style>
</head>
<body>
<div class="mingye">
<div class="mingba">
<div class="ming"></div>
</div>
</div>
</body>
<script type="text/javascript">
//事件冒泡,当子级元素触发某一个事件的时候,如果父级(父父级)也有对该事件的处理,都会执行.
//顺序是从子级才是一直追溯到docunment
var mingye=document.querySelector(".mingye");
var mingba=document.querySelector(".mingba");
var ming=document.querySelector(".ming");
mingye.onclick = function () {
console.log("我是明爷,我要去打小明");
}
mingba.onclick = function () {
console.log("我是明爸,我要去打小明");
}
ming.onclick = function (ev) {
var e = ev||event;
//取消事件冒泡
// e.cancelBubble=true;
// e.stopPropagation();
// 完整的写法
if(e.stopPropagation){
e.stopPropagation();
}else{
e.cancelBubble=true;
}
console.log("我是小明我要打自己");
}
</script>
</html>