contentEditable javascript caret placement in div

对着背影说爱祢 提交于 2019-12-04 15:48:39

问题


I have a contentEditable div.

Let's say the user clicks a button that inserts HTML into the editable area.

So, they click a button and the following is added to the innerHTML of the contentEditable div:

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

How do I automatically place the cursor (ie caret) IN the "inside" div? Worse. How can this work in IE and FF?


回答1:


For IE:

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

range.select();

For 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. In practice Webkit selects nothing and Opera selects the whole page. Sigh. This is still not well-supported territory.




回答2:


As far as i could understand from your question:

If it is contentEditable editable/typeable, you may try this:

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



回答3:


FYI focus() doesn't work for non-form elements with contentEditable enabled in Google Chrome (I just tried it on a <li> inside a list that is editable and nothing happened in Chrome 10.0.648.82 beta on Win XP Pro SP3).



来源:https://stackoverflow.com/questions/1892866/contenteditable-javascript-caret-placement-in-div

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!