JS中事件捕获
分类:前端面试题
事件流不是本篇文章重点,如果有兴趣,可以查看俺的这篇文章。
当一个事件发生在一个DOM元素上时,该事件不会完全发生在这个元素上。在捕获阶段,事件从window开始一直到触发事件的元素。
类似之前讲解JS中的事件冒泡,我们也下面这样的html结构:
<div class="grandparent">
<div class="parent">
<div class="child">1</div>
</div>
</div>
我们的JS代码如下:
function addEvent(el, event, callback, isCapture = false) {
if (!el || !event || !callback || typeof callback !== 'function') return;
if (typeof el === 'string') {
el = document.querySelector(el);
};
el.addEventListener(event, callback, isCapture);
}
addEvent(document, 'DOMContentLoaded', () => {
const child = document.querySelector('.child');
const parent = document.querySelector('.parent');
const grandparent = document.querySelector('.grandparent');
addEvent(child, 'click', function (e) {
console.log('child');
}, true);
addEvent(parent, 'click', function (e) {
console.log('parent');
}, true);
addEvent(grandparent, 'click', function (e) {
console.log('grandparent');
}, true);
addEvent(document, 'click', function (e) {
console.log('document');
}, true);
addEvent('html', 'click', function (e) {
console.log('html');
}, true)
addEvent(window, 'click', function (e) {
console.log('window');
}, true)
});
addEventListener方法有第三个可选参数useCapture,默认值为false,该事件将发生在冒泡阶段,如果为true,该事件将发生在捕获阶段。如果我们点击子元素,它会在控制台中分别打印window->document->html->grandParent->parent->child。这就是事件捕获。
该系列为面试题系列,俺的答案可能也存在瑕疵或不正确的地方,欢迎大家踊跃讨论。
一线大厂高级前端编写,前端初中阶面试题,帮助初学者应聘,需要联系微信:javadudu