事件冒泡和捕获

xiaoxiao2025-10-19  9

事件冒泡: 结构上(非视觉上)嵌套关系的元素,会存在事件冒泡的功能,即同一事件,自子元素冒泡向父元素。(自底向上) example: html:

<div class="box1"> <div class="box2"> <div class="box3"></div></div> </div>

css:

.box1{ width: 200px; height:200px; background-color:red; position: relative; } .box2{ width: 100px; height:100px; background-color: green; position: absolute; left: 0; top: 0; } .box3{ width: 50px; height:50px; background-color:yellow; position: absolute; left: 0; top: 0; }

js:

var box1 = document.getElementsByTagName('div')[0]; var box2 = document.getElementsByTagName('div')[1]; var box3 = document.getElementsByTagName('div')[2]; box1.addEventListener('click',function(){ console.log('box1') },false); box2.addEventListener('click',function(){ console.log('box2') },false); box3.addEventListener('click',function(){ console.log('box3') },false);

首先鼠标点击红色方块:打印box1 再点击绿色方块:打印box2 box1 最后点击黄色方块:打印box3 box2 box1 是结构上的嵌套,不是视觉上的,这样也是可以打印相同的结果出来

事件捕获: 结构上(非视觉上)嵌套关系的元素,会存在事件捕获的功能,即同一事件,自父元素捕获至子元素(事件源元素)。(自底向上) IE没有捕获事件

把false改成true就是事件捕获模型

box1.addEventListener('click',function(){ console.log('box1'); },true); box2.addEventListener('click',function(){ console.log('box2'); },true); box3.addEventListener('click',function(){ console.log('box3'); },true);

点击红色方块:box1 点击绿色方块:box1 box2 点击黄色方块:box1 box2 box3

结构上(非视觉上)嵌套关系的元素,会存在事件捕获的功能。

触发顺序,先捕获,后冒泡

特殊例子: 顺序一定是先捕获后冒泡,这没有问题,但是黄色区域是两个事件执行,事件执行的顺序要符合先后顺序,黄色的是先绑定冒泡再捕获。 focus,blur,change,submit,reset,select 等事件不冒泡

转载请注明原文地址: https://www.6miu.com/read-5038198.html

最新回复(0)