2

一些网站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" />

有谁知道这个问题的解决方法?

4

2 回答 2

7

得到答案,现在它适用于所有浏览器

<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" />
于 2013-04-03T17:17:56.457 回答
1

如果我没看错,您只需要防止焦点从父窗口转移到 iframe 中的元素。

我会在 iframe 元素上使用“onfocus”触发器将焦点切换回您的页面,如下所示:

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

如果(我怀疑你这样做)您只想防止 iframe 窃取初始焦点 onload 但希望用户能够稍后将焦点转移到它,请使用状态变量,如下所示:

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

我希望这会有所帮助,如果您有任何问题,我会在这里。

于 2013-04-03T16:31:40.420 回答