将光标设置在可编辑内容的末尾

Set cursor at the end of content editable

本文关键字:编辑 光标 设置      更新时间:2023-09-26

我有一个简单的可编辑内容,其中包含带标记的文本。。。当一个标签被插入时,单词会被里面的跨度替换…

<div contenteditable=true>
      text text text <span class="tag">tag</span> 
</div>

这就是结果(当用户按下空格键时,标签会被一个包含标签文本的跨度所取代;这种情况发生在按键上)

然后我需要将光标放在可编辑内容的末尾(范围外),以便用户继续键入。。。

我已经可以在末尾移动光标,但只能在范围内移动。。。

我用瘦腿。

这可能适用于

function moveCursorAtTheEnd(){
    var selection=document.getSelection();
    var range=document.createRange();
    var contenteditable=document.querySelector('div[contenteditable="true"]');
    if(contenteditable.lastChild.nodeType==3){
      range.setStart(contenteditable.lastChild,contenteditable.lastChild.length);
    }else{
      range.setStart(contenteditable,contenteditable.childNodes.length);
    }
    selection.removeAllRanges();
    selection.addRange(range);
  }

这也简单得多https://gist.github.com/al3x-edge/1010364

function setEndOfContenteditable(contentEditableElement)
{
    var range,selection;
    if(document.createRange)//Firefox, Chrome, Opera, Safari, IE 9+
    {
        range = document.createRange();//Create a range (a range is a like the selection but invisible)
        range.selectNodeContents(contentEditableElement);//Select the entire contents of the element with the range
        range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
        selection = window.getSelection();//get the selection object (allows you to change selection)
        selection.removeAllRanges();//remove any selections already made
        selection.addRange(range);//make the range you have just created the visible selection
    }
    else if(document.selection)//IE 8 and lower
    { 
        range = document.body.createTextRange();//Create a range (a range is a like the selection but invisible)
        range.moveToElementText(contentEditableElement);//Select the entire contents of the element with the range
        range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
        range.select();//Select the range (make it the visible selection
    }
}