gpt4 book ai didi

JavaScript mousedown 事件报告子节点而不是预期节点

转载 作者:行者123 更新时间:2023-12-02 17:01:21 28 4
gpt4 key购买 nike

我正在尝试向 DIV 添加一个简单的 mousedown 事件监听器。 DIV 有一个子节点,即 IMG。但是,当 mousedown 事件触发时,该事件的 targetsrcElement 属性引用的是 IMG,而不是DIV 节点。没有任何事件属性引用 DIV。该处理程序是通用的,需要事件中某处的实际节点,因此失败(它错误地尝试对 IMG 元素进行操作)。

我尝试过设置元素的 onmousedown 属性,以及调用我期望的元素的 .addEventListener('mousedown', f, true)阅读文档后,true 应该将事件直接分派(dispatch)到 DIV,而不是先将其发送到任何子节点。然而, child 仍然是唯一被报告为已收到事件的元素。我还尝试传递 false 而不是 true 而不做任何更改。

只有一个事件处理程序添加到 DIV 中,IMG 或其他任何地方都没有其他事件处理程序。

过去,我还没有足够通用的代码来要求它能够准确地知道哪个元素已注册了事件。我如何获得这些信息?

最佳答案

您可以使用event.currentTarget :

Identifies the current target for the event, as the event traverses the DOM. It always refers to the element the event handler has been attached to as opposed to event.target which identifies the element on which the event occurred.

或者,在大多数浏览器上您可以使用this。然而,我认为这是一种从未标准化的 DOM0 行为。

关于JavaScript mousedown 事件报告子节点而不是预期节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25676859/

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