[英]How to get focus back for parent window from an iframe programmatically in Javascript
Some websites have focus
set on an element on window load. 一些网站将focus
放在窗口加载的元素上。 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. 这仅发生在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? 有谁知道解决此问题的方法?
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" />
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. 希望对您有所帮助,如果您有任何疑问,我会在这里。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.