簡體   English   中英

如何使用Javascript以編程方式從iframe獲取父窗口的焦點

[英]How to get focus back for parent window from an iframe programmatically in Javascript

一些網站將focus放在窗口加載的元素上。 如果我內嵌該網站,則似乎無法以編程方式將焦點設置在父窗口上。 這僅發生在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" />

有誰知道解決此問題的方法?

得到了答案,現在可以在所有瀏覽器上使用

<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" />

如果我已正確閱讀此書,則只需要防止焦點從父窗口轉移到iframe中的某個元素即可。

我將在iframe元素上使用“ onfocus”觸發器,將焦點切換回您的頁面,如下所示:

<iframe width="800" height="500" src="http://www.bing.com" onfocus="document.getElementById('foo').focus();"/>

如果(我懷疑是這樣),如果您只是想防止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; }"/>

希望對您有所幫助,如果您有任何疑問,我會在這里。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM