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

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

问题描述

我有一个HTML文档中的一个点的坐标(X,Y)。如何确定哪些DOM节点在这些坐标?



有些想法:




  • 有没有我错过的DOM命中测试功能,需要一个点(X,Y)并返回DOM元素?

  • 有没有一个有效的方式来走DOM元素树找到包含的元素?这似乎是因为绝对定位的元素而变得棘手。

  • 有没有办法在给定(X,Y)位置模拟事件,以便浏览器最终创建一个事件对象有指向元素的指针?



(背景:我在本机应用程序中嵌入Qt的QWebView我正在尝试根据鼠标结束的DOM节点来改变Qt小部件提供的上下文菜单,但是Qt 4.5无法对DOM元素进行测试,尽管该功能正在4.6中,所以我希望能够将协调到Javascript,并用DOM API进行测试。)



谢谢!

解决方案

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


从文档
返回元素...这是
在给定点下的最高元素。


如果您需要支持旧版浏览器,除了你所建议的以外,我不能想到很多选项(遍历整个DOM,查看元素的位置和大小,看看它们是否包含你的(x,y))。



我不认为事件模拟工作,但这是一个有趣的想法。我对事件调度的理解是指定事件的目标,这正是您尝试首先找到的。


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

Some ideas:

  • Is there a DOM hit test function that I missed, that takes a point (X,Y) and returns the DOM element there?
  • Is there an efficient way to walk the DOM element tree to find the containing element? This seems like it would be tricky because of absolutely positioned elements.
  • Is there a way to simulate an event at a given (X,Y) position such that the browser ends up creating an event object that has a pointer to the element?

(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.)

Thanks!

解决方案

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.

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天全站免登陆