如何找到给定 (X,Y) 位置的 DOM 节点?(命中测试) [英] How do I find the DOM node that is at a given (X,Y) position? (Hit test)

查看:28
本文介绍了如何找到给定 (X,Y) 位置的 DOM 节点?(命中测试)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 HTML 文档中一个点的坐标 (X,Y).如何确定这些坐标处的 DOM 节点是什么?

I have the coordinates (X,Y) of a point in an HTML document. How do I determine what DOM node is at those coordinates?

一些想法:

  • 是否有我遗漏的 DOM 命中测试函数,它需要一个点 (X,Y) 并在那里返回 DOM 元素?
  • 是否有一种有效的方法可以遍历 DOM 元素树以查找包含元素?由于绝对定位的元素,这似乎很棘手.
  • 有没有办法在给定的 (X,Y) 位置模拟事件,以便浏览器最终创建一个具有指向元素的指针的事件对象?

(背景:我将 Qt 的 QWebView 嵌入到本机应用程序中.我试图根据鼠标悬停的 DOM 节点改变 Qt 小部件提供的上下文菜单,但 Qt 4.5 无法点击测试到DOM 元素,尽管该功能是在 4.6 中推出的.所以我希望我可以将坐标扔到 Javascript 中并在那里使用 DOM API 进行命中测试.)

(Background: I'm embedding Qt's QWebView in a native application. I'm trying to vary the context menu that the Qt widget provides based on the DOM node that the mouse is over, but Qt 4.5 cannot hit test to a DOM element, though that functionality is coming in 4.6. So I'm hoping I can toss the the coordinate into Javascript and do the hit testing there with DOM APIs.)

谢谢!

推荐答案

只要您的用户不使用旧版本的 Safari、Chrome 或 Opera,您就走运了:使用 document.elementFromPoint(x, y)(MSDN 参考Mozilla 参考QuirksMode 文章):

As long as your users aren't using old versions of Safari, Chrome or Opera, you're in luck: use document.elementFromPoint(x, y) (MSDN ref, Mozilla ref, QuirksMode article):

从文档中返回元素...这是最顶​​层的元素位于给定点之下.

Returns the element from the document ... which is the topmost element which lies under the given point.

如果你需要支持旧浏览器,除了你的建议我想不出很多选项(遍历整个 DOM,查看元素位置和大小,看看是否有任何一个封装了你的 (x, y)).

If you need to support older browsers, I can't think of many options other than what you suggest (traverse the entire DOM, looking at element positions and sizes and seeing if any of them encapsulate your (x, y)).

我不认为事件模拟会起作用,但这是一个有趣的想法.我对事件调度的理解是您指定事件的目标,这正是您首先要找出的目标.

I don't think the event simulation will work but it is an interesting idea. My understanding of event dispatching is you specify the target that the event is for, which is precisely what you are trying to find out in the first place.

这篇关于如何找到给定 (X,Y) 位置的 DOM 节点?(命中测试)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆