The above three nested div tags, if each div to define a click event, then click in when the div layer, it will click event to be exposed, and click events will lead to all the parent layer is executed
<!DOCTYPE html>
<html>
<head>
<title>学习事件</title>
<style type="text/css">
body{
border: 1px solid black;
}
div{
padding: 100px;
}
.div1{
background-color: red;
}
.div2{
background-color: green;
}
.div3{
background-color: gray;
}
</style>
<script type="text/javascript">
window.onload = function(){
};
</script>
</head>
<body>
<div class="div1" οnclick="alert('div1');">
<div class="div2" οnclick="alert('div2');">
<div class="div3" οnclick="alert('div3')">
</div>
</div>
</div>
</body>
</html>
Click the button below to achieve emerge div, click another part away, then the event will affect the bubble, execute the following code has no effect
<!DOCTYPE html>
<html>
<head>
<title>学习事件</title>
<style type="text/css">
div{
width: 100px;
height: 100px;
background-color: gray;
display: none;
}
</style>
<script type="text/javascript">
window.onload = function(){
var oBtn = document.getElementById('btn');
var oDiv = document.getElementById('div1');
oBtn.onclick = function(){
alert("click button");
oDiv.style.display = 'block';
}
document.onclick = function(){
alert("click document");
oDiv.style.display = 'none';
}
};
</script>
</head>
<body>
<input id="btn" type="button" value="点击">
<div id="div1"></div>
</body>
</html>
The following event bubbling removed, play a role in the
<!DOCTYPE html>
<html>
<head>
<title>学习事件</title>
<style type="text/css">
div{
width: 100px;
height: 100px;
background-color: gray;
display: none;
}
</style>
<script type="text/javascript">
window.onload = function(){
var oBtn = document.getElementById('btn');
var oDiv = document.getElementById('div1');
oBtn.onclick = function(ev){
var oEvent = ev || event;
// alert("click button");
oDiv.style.display = 'block';
oEvent.cancelBubble = true;//去掉冒泡事件
}
document.onclick = function(){
// alert("click document");
oDiv.style.display = 'none';
}
};
</script>
</head>
<body>
<input id="btn" type="button" value="点击">
<div id="div1"></div>
</body>
</html>