如何改变IFrame的焦点

pal*_*ogt 7 javascript iframe dom

我有一个带有一些按钮的IFrame.单击按钮时,将操纵父DOM(它们都在同一个域中,因此不必担心同源策略).

由于用户单击了按钮,焦点将转到IFrame.但是,我想将焦点移回父文档(主要是由于此FireFox问题).

我怎样才能做到这一点?

编辑:我创建了一个显示问题的js小提琴.虽然focus()如果你在父表单元素上调用它似乎工作,但它通常不起作用.从js-fiddle可以看出,我的父文档中没有表单元素.

Jim*_*ien 5

如果您想从 iframe 内部将焦点设置回外部窗口,则聚焦外部窗口本身不太可能向用户提供任何视觉反馈,因此最好将焦点集中在外部页面中的已知表单元素。

您可以按如下方式执行此操作:

外部.html

<html>
  <head>
    <title>Outer</title>
  </head>
  <body>
    <iframe id="iframe" src="inner.html">
    </iframe>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

内部.html

<html>
  <head>
    <title>Inner</title>
  </head>
  <body>
    <form id="innerForm">
      <input type="button" id="innerButton" value="Inner button" />
    </form>
  </body>
  <script type="text/javascript">
    // When we click the inner button...
    document.getElementById('innerButton').addEventListener('click', function() {
      /*
       * Do whatever you need to do here
       */

      // Focus the parent
      parent.focus();
    });
  </script>
</html>
Run Code Online (Sandbox Code Playgroud)

  • 啊,那行得通。不幸的是,你对FF的看法是对的。我在[此处]发现了一个错误(https://bugzilla.mozilla.org/show_bug.cgi?id=554039) (2认同)