我正在开发一个项目,将一个 eventListener 绑定(bind)到 <audio>
play
的元素event 和另一个 eventListener 到其父元素以获取同一事件。我注意到 child 的回调总是被调用,但 parent 的回调永远不会被调用。
如果我使用 addEventListener()
的捕获模式,然后两个回调都会正常调用 - 首先是父级,然后是子级。
为了进一步调查,我编写了一段代码,发现 play 事件不会冒泡回父级。
<!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>
这是输出:
parent-click-capture
child-click-capture
child-click-bubble
parent-click-bubble
parent-play-capture
child-play-capture
child-play-bubble
有谁知道这种行为是否仅适用于游戏事件,还是有其他事件不进入冒泡阶段(或捕获阶段)?
最佳答案
所有JS事件进入捕获
阶段。
可以通过读取事件的bubbles
property来检查事件是否进入冒泡
阶段。 .
element.addEventListener('ACTION', (e) => console.log(e.bubbles))
关于javascript - Javascript 中的所有事件都会捕获并冒泡吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36542744/