将重点放在Chrome中的iframe上 [英] Set focus on iframe in Chrome
本文介绍了将重点放在Chrome中的iframe上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在Chrome中有一个iframe( id:'chat'
),其 designMode ='on'
.
I have an iframe (id: 'chat'
) with designMode='on'
in Chrome.
在Enter键事件上,我调用了函数 send()
,该函数接收iframe内容并将其写入套接字.我的问题是,在清除iframe时,我失去了焦点.
On Enter keypress event I call the function send()
, which takes the iframe contents and writes it to a socket. My problem is that when clearing the iframe, I lose focus.
如何设置焦点,以便可以继续在iframe中键入文本?
How to do I set the focus so I can continue to type text in the 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);
}
我在其他问题上尝试了许多解决方案,但似乎没有一个起作用.
I've tried many of the solutions on other questions, but none seems to work.
推荐答案
诀窍是首先将重点放在身体上,然后创建 Range
.
The trick is to first set focus on the body and then create a 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);
这篇关于将重点放在Chrome中的iframe上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文