Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/395.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将光标设置在“内容可编辑”的末尾_Javascript_Contenteditable_Rangy - Fatal编程技术网

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

Javascript 将光标设置在“内容可编辑”的末尾,javascript,contenteditable,rangy,Javascript,Contenteditable,Rangy,我有一个简单的可编辑内容,包含带有标签的文本。。。当插入一个标记时,单词将被替换为其内部的一个span <div contenteditable=true> text text text <span class="tag">tag</span> </div> 文本标记 这是结果(当用户按空格键时,标记将替换为包含标记文本的跨距;这种情况发生在keyup上) 然后我需要将光标放在可编辑内容的末尾(在范围之外),以便让用户继续键入

我有一个简单的可编辑内容,包含带有标签的文本。。。当插入一个标记时,单词将被替换为其内部的一个span

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

文本标记
这是结果(当用户按空格键时,标记将替换为包含标记文本的跨距;这种情况发生在keyup上)

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

我已经能够在末尾移动光标,但只能在跨度内移动

我使用rangy。

这可能有用

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);

  }

这也更简单

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
    }
}