4

我在 Chrome 中有一个 iframe ( id: 'chat') 。designMode='on'

在 Enter keypress 事件中,我调用该函数send(),该函数获取 iframe 内容并将其写入套接字。我的问题是在清除 iframe 时,我失去了焦点。

如何设置焦点以便我可以继续在 iframe 中键入文本?

function send(){
    var $iframe = $('#chat');
    var text = $iframe.contents().text() + "\n";  

    socket.send(text);

    // When this is done, the focus is lost
    // If commented, the focus will not be lost
    $iframe.contents().find('body').empty();

    // My different failed attempts to regain the focus
    //$iframe.focus();
    //$iframe.contents().focus();
    //$iframe.contents().find('body').focus();
    //$iframe.contents().find('body').parent().focus();
    //$iframe[0].contentWindow.focus();

    // I've also tried all the above with timers
    //setTimeout( function(){ $('#chat').contents().focus(); }, 100);
}

我已经尝试了许多其他问题的解决方案,但似乎没有一个有效。

4

4 回答 4

3

诀窍是首先将焦点放在身体上,然后创建一个Range.

var win = iframe.contentWindow;
var range = win.document.createRange();
range.setStart(win.document.body, 0);
range.setEnd(win.document.body, 0);
win.document.body.focus();
win.getSelection().addRange(range);
于 2011-11-13T11:20:43.693 回答
2

这个问题已经回答here

基本上,如果您不刷新 iframe,您可以使用:

$iframe[0].contentWindow.focus();

请注意,我正在抓取底层 iframe DOM 对象。

于 2011-11-13T10:56:46.310 回答
1

我尝试了以下解决方案,它适用于所有浏览器(IE/Chrome/Firefox)

上下文:我想一直关注 iframe。

    function IFocus() {
        var iframe = $("#iframeId")[0];
        iframe.contentWindow.focus();
    };
    window.setInterval(IFocus, 300);

希望对大家有帮助,有需要的朋友...

于 2016-08-22T12:01:43.807 回答
0

我用 Chrome 测试了这个解决方案。我最初将它发布在Setting focus to iframe contents中。

这是使用 jQuery 创建 iframe 的代码,将其附加到文档中,轮询它直到它被加载,然后聚焦它。这比设置任意超时要好,这取决于 iframe 加载所需的时间,可能会或可能不会起作用。

var jqueryIframe = $('<iframe>', {
    src: "http://example.com"
}),
focusWhenReady = function(){
    var iframe = jqueryIframe[0],
    doc = iframe.contentDocument || iframe.contentWindow.document;
    if (doc.readyState == "complete") {
        iframe.contentWindow.focus();
    } else {
        setTimeout(focusWhenReady, 100)
    }
}
$(document).append(jqueryIframe);
setTimeout(focusWhenReady, 10);

检测 iframe 何时加载的代码改编自Biranchi如何检查 iframe 是否已加载或是否有内容的回答?

于 2015-04-14T12:01:43.337 回答