javascript - 触发文档中其他任何地方的点击,即使使用 iframe?

标签 javascript iframe

所以我正在创建一个小部件,如果用户点击它以外的任何地方,它应该“关闭”。

显而易见的解决方案是在文档上放置一个点击处理程序。这很好,除了应用程序的其他部分使用 event.stopPropagation()。所以我们在监听器中使用捕获阶段来解决这个问题。

这似乎适用于所有内容,除了在 iframe 上。我做了一个simple jsfiddle to demonstrate what I'm talking about .代码抄本:

var c = document.getElementById('clickme');
var s = document.getElementById('stop');
var t = document.getElementById('text');

document.addEventListener('click', function (event) {
  if (event.target !== c) {
    t.innerHTML += 'outside <br>';
  } else {
    t.innerHTML += 'inside <br>';
  }
}, true); //true to use capturing phase

s.addEventListener('click', function (event) {
  event.stopPropagation();
});

和设置:

<html>
<body>
  <p>Clicking anywhere but the button counts as an 'outside' click. However, clicks within the iframe do not trigger the event listener.</p>
  <div><button id="clickme">Click me!</button></div>
  <iframe>lalala</iframe>
  <div><button id="stop">Even Me, and I stopPropagation()</button></div>
  <div id="text"></div>
</body>
</html>

有没有办法让这个处理程序也触发 iframe 内/上的点击?此外,在我附加事件监听器时,我不会引用 iframe,因此不需要它的解决方案是最好的。

最佳答案

只有当 iframe 位于同一域中时,您才能检测到 iframe 中的点击事件。在 JavaScript: Detection of a link click inside an iframe 查看@Tim Down 的回答

如果 iframe 在另一个域上,您可以利用单击 iframe 时文档上会发生模糊事件这一事实。您需要在 body 元素上设置一个 tabIndex 才能正常工作:

document.body.tabIndex= 0;

document.addEventListener('blur', function (event) {
  t.innerHTML += 'outside <br>';
}, true);

请注意,在 iframe 中多次点击只会触发一个模糊事件。

fiddle : http://jsfiddle.net/zrgrt9pf/13/

关于javascript - 触发文档中其他任何地方的点击,即使使用 iframe?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26475422/

相关文章:

javascript - 在 Javascript 中,获取匹配正则表达式的长度

javascript - 如何在 asp.net 中的文本框占位符中使用 mathjax?

javascript - 如何在 jQuery 中发出 put 请求

javascript - 将实例变量传递给 js Rails

iframe - 如何在 Sproutcore 的 View 中添加iframe?

javascript - Feed.ly 如何确定 iFrame 加载进度?

javascript - 在 firefox 扩展中读取本地 json 文件

C# Selenium Webdriver 在 iframe 中查找元素

javascript - 如何将动态 javascript 代码注入(inject)父页面上已存在的 iframe 中

jquery - 为什么我的 iFrame 不能像我需要的那样加宽?