问题描述
我已阅读但无法理解 useCapture
属性。定义有:
I have read article at https://developer.mozilla.org/en/DOM/element.addEventListener but unable to understand useCapture
attribute. Definition there is:
在此代码中,父事件在子事件之前触发,因此我无法理解其
行为。文档对象具有usecapture true和子div的usecapture设置为false并且文档usecapture被跟随。所以为什么文档属性优先于child。
In this code parent event triggers before child,so I am not able to understand itsbehavior.Document object has usecapture true and child div has usecapture set false and document usecapture is followed.So why document property is preferred over child.
function load() {
document.addEventListener("click", function() {
alert("parent event");
}, true);
document.getElementById("div1").addEventListener("click", function() {
alert("child event");
}, false);
}
<body onload="load()">
<div id="div1">click me</div>
</body>
推荐答案
事件可以两次激活:开始(捕获)和结束(冒泡)。
事件按照定义的顺序执行。比如说,你定义了4个事件监听器:
Events can be activated at two occasions: At the beginning ("capture"), and at the end ("bubble").Events are executed in the order of how they're defined. Say, you define 4 event listeners:
window.addEventListener("click", function(){alert(1)}, false);
window.addEventListener("click", function(){alert(2)}, true);
window.addEventListener("click", function(){alert(3)}, false);
window.addEventListener("click", function(){alert(4)}, true);
警告框将按以下顺序弹出:
The alert boxes will pop up in this order:
-
2
(首先定义,使用capture = true
) -
4
(使用capture = true
定义第二个) -
1
(首次定义的事件capture = false
) -
3
(第二个定义的事件capture = false
)
2
(defined first, usingcapture=true
)4
(defined second usingcapture=true
)1
(first defined event withcapture=false
)3
(second defined event withcapture=false
)
这篇关于无法理解addEventListener中的useCapture参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!