javascript 如何将焦点移出 IFrame

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10502099/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 10:06:06  来源:igfitidea点击:

how to change focus out of IFrame

javascriptdomiframe

提问by paleozogt

I have an IFrame with some buttons in it. When the buttons are clicked, the parent DOM is manipulated (it's all in the same domain, so don't worry about the same-origin policy).

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

Since the user clicked on a button, the focus goes to the IFrame. However, I'd like to move the focus back to the parent document (mostly due to this FireFox problem).

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

How can I do this?

我怎样才能做到这一点?

Edit:I've created a js-fiddlethat shows the problem. While focus()seems to work if you call it on parent form elements, it doesn't work in general. As you can see from the js-fiddle there are no form elements in my parent document.

编辑:我创建了一个显示问题的js-fiddle。而focus()如果你把它的父表单元素似乎工作,但它不是一般的工作。正如您从 js-fiddle 中看到的,我的父文档中没有表单元素。

采纳答案by Jim O'Brien

If you want to set the focus back to the outer window from inside the iframe, focussing the outer window itself is unlikely to give any visual feedback to the user, so it is better to focus a known form element in the outer page.

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

You can do this as follows:

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

outer.html

外部.html

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

inner.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>

回答by Elliot Bonneville

Make an eleemnt on your page and call this at some point after focus is set to the IFrame:

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

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

That will set the focus back to the body and out of the IFrame.

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