在Javascript捕获和气泡中执行所有事件

Do all events in Javascript capture and bubble?

本文关键字:执行 事件 气泡 Javascript      更新时间:2024-04-11

我正在处理一个项目,在该项目中,我将一个eventListener绑定到play事件的<audio>元素,并将另一个event监听器绑定到同一事件的父元素。我注意到孩子的回调总是被调用的,但家长的回调从来没有被调用过。

如果我使用addEventListener()的捕获模式,那么两个回调都被正常调用——首先调用父调用,然后调用子调用。

为了进一步调查,我写了一段代码,发现播放事件不会回到父级。

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <div><audio src="song.mp3" controls="true"></audio></div>
</body>
<script type="text/javascript">
    parent = document.querySelector('div');
    child = document.querySelector('div audio');
    parent.addEventListener('click', function() {console.log('parent-click-capture');}, true);
    parent.addEventListener('click', function() {console.log('parent-click-bubble');}, false);
    parent.addEventListener('play', function() {console.log('parent-play-capture');}, true);
    parent.addEventListener('play', function() {console.log('parent-play-bubble');}, false);
    child.addEventListener('click', function() {console.log('child-click-capture');}, true);
    child.addEventListener('click', function() {console.log('child-click-bubble');}, false);
    child.addEventListener('play', function() {console.log('child-play-capture');}, true);
    child.addEventListener('play', function() {console.log('child-play-bubble');}, false);
</script>
</html>

这就是输出:

父单击捕获
子点击捕获
子点击气泡
父级单击气泡
家长游戏捕获
儿童游戏捕捉
儿童游戏气泡


有人知道这种行为是否只是游戏事件的特殊行为,或者还有其他事件没有进入泡沫阶段(或捕捉阶段)吗?

所有JS事件都进入capture阶段。

可以通过读取事件的bubbles属性来检查事件是否进入bubble阶段。

element.addEventListener('ACTION', (e) => console.log(e.bubbles))