一、定义
事件捕获:首先是 window 会捕获到事件,之后 document、documentElement、body会捕获到,再之后就是在 body 中 DOM 元素一层一层的向下捕获到事件;
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<style>
.div1,
.isp{
margin: 5px;
padding: 5px;
box-sizing: border-box;
}
.div1{
width: 500px;
height: 500px;
background: green;
}
.isp{
width: 200px;
height: 200px;
background: blue;
}
</style>
<body>
<div class="div1" >
<p class="isp" ></p>
</div>
</body>
</html>
<script>
var div1 = document.getElementsByClassName('div1')[0]
var isp = document.getElementsByClassName('isp')[0]
// 事件捕获
window.addEventListener("click", function(e) {
console.log("window 层捕获", e.target.nodeName, e.currentTarget.nodeName)
}, true)
document.addEventListener("click", function(e) {
console.log("document 层捕获", e.target.nodeName, e.currentTarget.nodeName)
}, true)
document.documentElement.addEventListener("click", function(e) {
console.log("documentElement 层捕获", e.target.nodeName, e.currentTarget.nodeName)
}, true)
document.body.addEventListener("click", function(e) {
console.log("body 捕获", e.target.nodeName, e.currentTarget.nodeName)
}, true)
div1.addEventListener("click", function(e) {
console.log("div1 节点捕获", e.target.nodeName, e.currentTarget.nodeName)
}, true)
isp.addEventListener("click", function(e) {
console.log("isp 节点捕获", e.target.nodeName, e.currentTarget.nodeName)
}, true)
</script>
事件冒泡:同捕获阶段相反,事件一层一层的向上冒泡回到 window;
<script>
var div1 = document.getElementsByClassName('div1')[0]
var isp = document.getElementsByClassName('isp')[0]
// 冒泡事件
isp.addEventListener("click", function(e) {
console.log("isp 冒泡", e.target.nodeName, e.currentTarget.nodeName)
}, true)
div1.addEventListener("click", function(e) {
console.log("div1 冒泡", e.target.nodeName, e.currentTarget.nodeName)
}, true)
document.body.addEventListener("click", function(e) {
console.log("body 冒泡", e.target.nodeName, e.currentTarget.nodeName)
}, true)
document.documentElement.addEventListener("click", function(e) {
console.log("documentElement 层冒泡", e.target.nodeName, e.currentTarget.nodeName)
}, true)
document.addEventListener("click", function(e) {
console.log("document 冒泡", e.target.nodeName, e.currentTarget.nodeName)
}, false)
window.addEventListener("click", function(e) {
console.log("window 冒泡", e.target.nodeName, e.currentTarget.nodeName)
}, false)
</script>
所以,完整的 js 事件流,就是从 window 开始,最后又回到 window 的过程。
二、事件委托(事件代理)
$("节点").on("事件名称", function(e) {
$(e.target).....
})