gpt4 book ai didi

javascript - 确定 DOM 事件冒泡中的事件路径

转载 作者:技术小花猫 更新时间:2023-10-29 12:45:16 25 4
gpt4 key购买 nike

我正在尝试找出事件冒泡的路径。例如,我有这样的标记

 <div id="container" onclick="func">
<div id="div1"></div>
<div id="div2">
<div id="div2.1"></div>
<span id="span2.2"></span>
<div id="div2.3">
<button id="btn2.3.1"></button>
</div>
</div>
</div>

现在,如果单击 btn2.3.1,我希望看到事件冒泡的整个路径,即 btn2.3.1 -> div2.3 -> div2 ->container 。有没有办法只在容器上放置一个处理程序来做到这一点? (请不要使用 Jquery)

我找到了一个 event.path 数组。这是做什么的,但找不到关于它的详细信息。它是跨浏览器的吗?实现这一目标的正确方法是什么?

最佳答案

事件路径 || event.composedPath()

事件路径

polymer project documentation 中的注释和通过 an HTML5Rocks article 发现/未覆盖,pathArray 形式的家谱。

它似乎是event 接口(interface)的扩展”,仅通过 Web Component Shadow DOM 公开,并且是标准 只有在这方面(显然),似乎没有很多可用的文档,并且它没有在所有浏览器中公开(默认情况下)。

event.composedPath() 助您一臂之力!

另一个 question about the use of pathanswered with a suggestion to use composedPath ...

MDNdocumentation about event.composedPath() 是这样描述的:

The composedPath() method of the Event interface returns the event’s path which is an array of the objects on which listeners will be invoked. This does not include nodes in shadow trees if the shadow root was created with its ShadowRoot.mode closed.

WHATWGtheir "DOM specs" documentation about the "event path"是这样描述的:

Returns the invocation target objects of event’s path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root’s mode is "closed" that are not reachable from event’s currentTarget.

Can I use... 指出 browser support of composedPath() 很普遍,IE 和 Edge 落后,没有可预见的支持,MDN 同意这一点。

WHATWG's documentation about "dispatching events" 详细说明“事件的路径”将包含项目 appended 的条件。

详情于 2019 年 9 月 25 日更正

实际演示

const green = document.getElementById( 'green' ),
msg = document.querySelector( 'output' );

document.getElementById( 'red' ).addEventListener( 'click', evt => {
msg.innerHTML = '"' + evt.target.id + '" got poked, and "green" was' +

/* access to the event path */
( ~evt.composedPath().indexOf( green ) ? '' : "<b>n't</b>" )

+ ' in the path.';
} );
div { display: inline-block; padding: 1em 3em 1em 1em; cursor: pointer }
output { font-family: monospace; display: block; margin-top: 1em }
#red { background: red }
#green { background: green }
#blue { background: blue }
<div id="red">
<div id="green">
<div id="blue"></div>
</div>
</div>
<output>Poke the DOM!</output>

关于javascript - 确定 DOM 事件冒泡中的事件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26195091/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com