目录
Event
1. event.target
2. event.eventPhase
3. event.currentTarget
4. 事件捕获
5. 事件冒泡
6. onclick & addEventListener
7. 例子🌰
点击 div#d2 后的打印效果
Event
1. event.target
触发事件的目标元素
2. event.eventPhase
0Event.NONE (没有事件)1Event.CAPTURING_PHASE(捕获阶段)2Event.AT_TARGET(事件传播到目标元素)3Event.BUBBLING_PHASE(冒泡阶段)3. event.currentTarget
事件是在不断传播的,而currentTarget 代表事件当前传到的元素
4. 事件捕获
从根元素(document)传播向下到目标元素的过程
5. 事件冒泡
从目标元素向上传播到根元素(document)上的过程
6. onclick & addEventListener
x.addEventListener(type, listener, useCapture);
注意第三个参数,默认是 false
true:事件捕获是触发事件false: 事件冒泡是触发事件
使用 onclick 形式在元素上加事件的,默认 useCapture 为 false
<body οnclick="fn(evnet)">
7. 例子🌰
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Event</title></head><body><div id="d1" style="color: #000; background:rgba(220,38,38,0.2);">d1<div id="d2" style="margin: 20px; color: #000; background:rgba(220,38,38,0.2);">d2<div id="d3" style="margin: 20px; color: #000; background:rgba(220,38,38,0.2);">d3</div></div></div></body></html><script>function generateClickFn(e) {console.log(`触发事件的是:${e.target.id || e.target.nodeName},事件所处阶段: ${e.eventPhase},事件传播到: ${e.currentTarget.id || e.currentTarget.nodeName}`);}let d1 = document.getElementById('d1');let d2 = document.getElementById('d2');let d3 = document.getElementById('d3');d1.addEventListener('click', generateClickFn);d2.addEventListener('click', generateClickFn);d3.addEventListener('click', generateClickFn);document.addEventListener('click', generateClickFn);document.body.addEventListener('click', generateClickFn);d1.addEventListener('click', generateClickFn, true);d2.addEventListener('click', generateClickFn, true);d3.addEventListener('click', generateClickFn, true);document.addEventListener('click', generateClickFn, true);document.body.addEventListener('click', generateClickFn, true);</script>