8

我有一个 IFrame,里面有一些按钮。当按钮被点击时,父 DOM 被操作(它们都在同一个域中,所以不用担心同源策略)。

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

我怎样才能做到这一点?

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

4

2 回答 2

4

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

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

外部.html

<html>
  <head>
    <title>Outer</title>
  </head>
  <body>
    <iframe id="iframe" src="inner.html">
    </iframe>
  </body>
</html>

内部.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>
于 2012-05-08T16:45:34.290 回答
0

在您的页面上创建一个元素,并在焦点设置为 IFrame 后的某个时间点调用它:

document.getElementById("myElementId").focus(); 

这会将焦点设置回正文并移出 IFrame。

于 2012-05-08T16:03:27.027 回答