一.事件冒泡
事件冒泡:从当前触发的事件目标一级一级往上传递,依次触发,直到document为止。
举例代码:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
#listinfo
{
border: 10px solid mediumpurple;
}
</style>
</head>
<body>
<div id="box" style="width: 100px; height: 100px; background-color: pink">
<button id="box_btn">按钮</button>
</div><br/><br/>
<script>
var num = 0;
//添加按钮事件
box_btn.onclick = function () {
num++;
console.log(this,num);
var e = window.event || event;//event是事件对象,也可以以形参的形式写在事件的执行函数上
e.cancelBubble = true;
}
//添加div事件
box.onclick = function () {
num++;
console.log(this,num);
}
</script>
</body>
</html>
控制台输出:
二.事件捕获
事件捕获:从document开始触发,一级一级往下传递,依次触发,直到真正事件目标为止。
举例代码:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="block" style=" width: 100px; height: 100px; border: 1px solid plum;">
<button id="block_btn">按钮</button>
</div><br/><br/>
<script>
block.addEventListener("click", function () {
console.log("div的事件");
},true);
block_btn.addEventListener("click",function () {
console.log("button的事件");
},false);
</script>
</body>
</html>
控制台输出:
三.事件委托
事件委托:把原本需要绑定在子元素的响应事件委托给父元素,让父元素监听。
举例代码:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
.nav
{
width: 100%;
height: 500px;
background-color: aquamarine;
padding: 10px;
}
.nav > li
{
line-height: 100px;
background-color: palegreen;
margin: 20px 0;
list-style: none;
}
</style>
</head>
<body>
<ul class="nav">
<li>蔬菜</li>
<li>水果</li>
<li>肉</li>
<li>面</li>
</ul>
<script>
var nav = document.querySelector(".nav");
nav.onclick = function (e) {
//将事件委托给子元素来执行
if (e.target.nodeName.toLowerCase() == "li") {
console.log("事件执行");
}
}
</script>
</body>
</html>
控制台输出:
注:当点击li内部时,事件执行;点击li之外的区域,事件不执行。