document.elementFromPoint(x,y) 获取 iframe 内的元素

Ana*_*tit 2 html javascript

我正在尝试获取 html 页面中的元素,我使用 document.elementFromPoint(x,y) 来检测输入元素;当没有 iframe 时它工作正常。但是在 iframes 中它在这段代码中不起作用

html如下

我错过了什么吗?

<html>
...
<div>
<div>
<iframe src="some source"..>  
<html>
..
<form>
<fieldset>
<input>
Run Code Online (Sandbox Code Playgroud)

谢谢

Dan*_*ses 5

根据此处的文档:

“如果指定点的元素属于另一个文档(例如,iframe 的子文档),则返回调用该方法的文档的 DOM 中的元素(在 iframe 情况下,iframe 本身)。”

这意味着如果您当前的 DOM 上下文是 iframe 的父级,它应该返回 iframe。还有一些跨域安全问题,你应该如果iframe是从另一个域读了。

如果它来自您的域并且您希望在 iframe 中获取元素,则可以执行以下操作:

var el = document.elementFromPoint(x, y);
if (el instanceof HTMLIFrameElement)
    el = el.contentWindow.document.elementFromPoint(x, y);  //Not sure if you need to update x, y to account for being inside another dom.
Run Code Online (Sandbox Code Playgroud)