如何在 Javascript 中以编程方式从 iframe 重新获得父窗口的焦点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15792620/
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
How to get focus back for parent window from an iframe programmatically in Javascript
提问by user1643156
Some websites have focus
set on an element on window load. If I iframe that website, It seems not able to set focus on parent window, programmatically. This only happens to IE
(9) and Firefox
(19), Opera/Safari/Chrome are fine.
一些网站focus
在窗口加载时设置了一个元素。如果我 iframe 该网站,它似乎无法以编程方式将焦点设置在父窗口上。这只发生在IE
(9) 和Firefox
(19) 中,Opera/Safari/Chrome 都可以。
<script>
window.onload = function() {
setTimeout(function() {
// this does not focus #foo
document.getElementById("foo").focus();
// or more seconds that enough to see the iframe focus
}, 3000);
};
</script>
<input id="foo" type="text" value="foo" /><br />
<iframe width="800" height="500" src="http://www.bing.com" />
Does anyone know a workaround for this problem?
有谁知道这个问题的解决方法?
回答by user1643156
Got the answer, now it works on all browsers
得到了答案,现在它适用于所有浏览器
<script>
window.onload = function() {
// blur the iframe
document.getElementById("bing").blur();
// set focus on #foo
document.getElementById("foo").focus();
// when iframe tries to focus, focus #foo
document.getElementById("foo").onblur = function() {
this.focus();
};
};
</script>
<input id="foo" type="text" value="foo" /><br />
<iframe id="bing" width="800" height="500" src="http://wwww.bing.com" />
回答by Marvin
If I've read this correctly you just need to prevent the focus being shifted from the parent window to an element in the iframe.
如果我没看错,你只需要防止焦点从父窗口转移到 iframe 中的一个元素。
I would use an 'onfocus' trigger on the iframe element to switch the focus back to your page, like so:
我会在 iframe 元素上使用“onfocus”触发器将焦点切换回您的页面,如下所示:
<iframe width="800" height="500" src="http://www.bing.com" onfocus="document.getElementById('foo').focus();"/>
If (as I suspect you do) you only want to prevent the iframe stealing the initial focus onload but would like the user to be able to shift focus to it later, use a status variable, like so:
如果(正如我怀疑您所做的那样)您只想防止 iframe 在加载时窃取初始焦点,但希望用户能够稍后将焦点转移到它,请使用状态变量,如下所示:
<script type="text/javascript">
var initialFocus = false;
</script>
<iframe width="800" height="500" src="http://www.bing.com" onfocus="if (initialFocus==false) { document.getElementById('foo').focus(); initialFocus = true; }"/>
I hope this helps and I'm here if you have any questions.
我希望这会有所帮助,如果您有任何问题,我会在这里。