从 JavaScript 以编程方式触发 DOM 鼠标事件

发布于 2024-09-15 22:23:16 字数 465 浏览 1 评论 0原文

是否可以在 DOM 中以编程方式触发鼠标事件?我的示例案例如下:

<html>
  <body>
    <iframe style="width: 500px; height: 500px;" src="something.html"></iframe>
    <div id="layer" style="position: absolute; left: 0px; top=0px; width=500px; height=500px;"></div>
  </body>
</html>

每当用户单击 iframe 上的 div 时,我想以某种方式将事件传播到 iframe , 也。 (这里我们假设iframe src位于同一个域中。)

Is it possible to programmatically fire mouse events in DOM? My sample case would be the following:

<html>
  <body>
    <iframe style="width: 500px; height: 500px;" src="something.html"></iframe>
    <div id="layer" style="position: absolute; left: 0px; top=0px; width=500px; height=500px;"></div>
  </body>
</html>

Whenever the user clicks the div over an iframe, I would like to somehow propagate the event to the iframe, too. (Here we assume that the iframe src is in the same domain.)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

千纸鹤带着心事 2024-09-22 22:23:16

虽然您可以将事件注入浏览器的事件处理系统(以不完全可移植的方式),但这只会导致调用在这些事件上注册的事件处理程序。它不会导致默认操作,例如跟踪单击的链接。此外,您无法从坐标中为您计算出目标元素,因此您必须自己完成此操作。

更好的选择是放弃模糊的

并在 iframe 的文档上注册一个 click 处理程序,然后通知父级中的代码单击的位置。

Whilst you can inject events into browsers' event-handling systems (in not entirely portable ways), it will only cause event handlers registered on those events to be called. It won't cause default actions like following clicked links. Also you don't get the target element worked out for you from co-ordinates so you'd have to do that yourself.

A better bet would be to lose the obscuring <div> and register a click handler on the iframe's document, which then informs code in the parent of the location of the click.

蓝眼睛不忧郁 2024-09-22 22:23:16

如果您遇到过 的父级和子级位于不同域的情况,我建议您学习使用 postMessage()

使用 postMessage() 你可以监听 "message" 事件,如下所示:

window.addEventListener("message", (event) => {}

https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

我想添加这个,因为有一段时间回来后,我很难找到最好的方法。另外,当您想要控制事物、想要在 iframe 中监听时,postMessage() 也很有用。

If you ever are in a situation, where you have <iframe>s parent and child in different domains, I recommend learning to use postMessage().

With postMessage() you can listen "message"event like so:

window.addEventListener("message", (event) => {}

https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

I wanted to add this, because a while back, I had a hard time finding the best way to do it. Also, postMessage() is useful in situations, when you want to control things, you want to listen in an iframe.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文