简体   繁体   English

contentEditable javascript插入div中的插入符号

[英]contentEditable javascript caret placement in div

I have a contentEditable div. 我有一个contentEditable div。

Let's say the user clicks a button that inserts HTML into the editable area. 假设用户单击一个将HTML插入可编辑区域的按钮。

So, they click a button and the following is added to the innerHTML of the contentEditable div: 因此,他们单击一个按钮,并将以下内容添加到contentEditable div的innerHTML中:

<div id="outside"><div id="inside"></div></div>

How do I automatically place the cursor (ie caret) IN the "inside" div? 如何自动将光标(即插入符号)放在“内部”div中? Worse. 更差。 How can this work in IE and FF? 如何在IE和FF中工作?

For IE: 对于IE:

var range= document.body.createTextRange();
range.moveToElementText(document.getElementById('inside'));

range.select();

For Mozilla: 对于Mozilla:

var range= document.createRange();
range.selectNodeContents(document.getElementById('inside'));

var selection= window.getSelection();
selection.removeAllRanges();
selection.addRange(range);

In theory the Mozilla version should also work in Webkit and Opera. 从理论上讲,Mozilla版本也应该适用于Webkit和Opera。 In practice Webkit selects nothing and Opera selects the whole page. 在实践中,Webkit不会选择任何内容,Opera会选择整个页面。 Sigh. 叹。 This is still not well-supported territory. 这仍然不是很好的支持领土。

As far as i could understand from your question: 据我所知,你的问题是:

If it is contentEditable editable/typeable, you may try this: 如果contentEditable是可编辑/可输入的,您可以尝试这样做:

  // you insert content with your code and after that
  document.getElementById('contentEditable_id_here').focus();

FYI focus()不适用于在Google Chrome中启用了contentEditable的非表单元素(我只是在一个可编辑的列表中的<li>上试了一下,在Win XP Pro SP3上的Chrome 10.0.648.82 beta中没有发生任何事情) 。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM