如何将光标移动到可信实体的末尾

avs*_*sej 73 javascript contenteditable cursor-position

我需要contenteditable像在Gmail备注小部件上一样将插入符移动到节点的末尾.

我在StackOverflow上读取了线程,但这些解决方案基于使用输入,它们不适用于contenteditable元素.

Nic*_*rns 217

Geowa4的解决方案适用于textarea,但不适用于满足要求的元素.

该解决方案用于将插入符号移动到可满足元素的末尾.它应该适用于所有支持contenteditable的浏览器.

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
    }
}
Run Code Online (Sandbox Code Playgroud)

它可以被类似的代码使用:

elem = document.getElementById('txt1');//This is the element that you want to move the caret to the end of
setEndOfContenteditable(elem);
Run Code Online (Sandbox Code Playgroud)

  • Nico的`selectNodeContents`部分给了我Chrome和FF的错误(没有测试其他浏览器),直到我发现我显然需要将`.get(0)`添加到我正在为该函数提供的元素中.我想这与我使用jQuery而不是裸JS有关?我在[问题4233265](http://stackoverflow.com/questions/4233265/contenteditable-set-caret-at-the-end-of-the-text-cross-browser)从@jwarzech那里学到了这一点.谢谢大家! (7认同)
  • 是的,该函数需要DOM元素,而不是jQuery对象.`.get(0)`检索jQuery内部存储的dom元素.你也可以在这个上下文中附加`[0]`,这相当于`.get(0)`. (5认同)
  • 这是这个问题的正确答案,完美,谢谢Nico. (4认同)

Vit*_*ile 24

还有另一个问题.

尼科伯恩斯如果的解决方案工作contenteditableDIV不包含其他元素multilined.

例如,如果div包含其他div,并且这些其他div包含其他内容,则可能会出现一些问题.

为了解决这些问题,我安排了以下解决方案,即Nico的改进:

//Namespace management idea from http://enterprisejquery.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-1/
(function( cursorManager ) {

    //From: http://www.w3.org/TR/html-markup/syntax.html#syntax-elements
    var voidNodeTags = ['AREA', 'BASE', 'BR', 'COL', 'EMBED', 'HR', 'IMG', 'INPUT', 'KEYGEN', 'LINK', 'MENUITEM', 'META', 'PARAM', 'SOURCE', 'TRACK', 'WBR', 'BASEFONT', 'BGSOUND', 'FRAME', 'ISINDEX'];

    //From: https://stackoverflow.com/questions/237104/array-containsobj-in-javascript
    Array.prototype.contains = function(obj) {
        var i = this.length;
        while (i--) {
            if (this[i] === obj) {
                return true;
            }
        }
        return false;
    }

    //Basic idea from: https://stackoverflow.com/questions/19790442/test-if-an-element-can-contain-text
    function canContainText(node) {
        if(node.nodeType == 1) { //is an element node
            return !voidNodeTags.contains(node.nodeName);
        } else { //is not an element node
            return false;
        }
    };

    function getLastChildElement(el){
        var lc = el.lastChild;
        while(lc && lc.nodeType != 1) {
            if(lc.previousSibling)
                lc = lc.previousSibling;
            else
                break;
        }
        return lc;
    }

    //Based on Nico Burns's answer
    cursorManager.setEndOfContenteditable = function(contentEditableElement)
    {

        while(getLastChildElement(contentEditableElement) &&
              canContainText(getLastChildElement(contentEditableElement))) {
            contentEditableElement = getLastChildElement(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
        }
    }

}( window.cursorManager = window.cursorManager || {}));
Run Code Online (Sandbox Code Playgroud)

用法:

var editableDiv = document.getElementById("my_contentEditableDiv");
cursorManager.setEndOfContenteditable(editableDiv);
Run Code Online (Sandbox Code Playgroud)

这样,光标肯定位于最后一个元素的末尾,最终嵌套.

编辑#1:为了更通用,while语句还应考虑所有其他不能包含文本的标记.这些元素被命名为void元素,在这个问题中,有一些方法可以测试元素是否为void.因此,假设存在一个被调用的函数canContainText,true如果参数不是void元素则返回,以下代码行:

contentEditableElement.lastChild.tagName.toLowerCase() != 'br'
Run Code Online (Sandbox Code Playgroud)

应替换为:

canContainText(getLastChildElement(contentEditableElement))
Run Code Online (Sandbox Code Playgroud)

编辑#2:上述代码已完全更新,描述和讨论的每个更改


Fri*_*ich 20

selection仅使用(不使用)的更短且可读的版本range

function setEndOfContenteditable(elem) {
    let sel = window.getSelection();
    sel.selectAllChildren(elem);
    sel.collapseToEnd();
}
Run Code Online (Sandbox Code Playgroud)
<p contenteditable>
A paragraph <span id="txt1" style="background: #cec">span text node <i>span italic</i></span> a paragraph.
<p>

<button onclick="setEndOfContenteditable(txt1)">set caret</button>
Run Code Online (Sandbox Code Playgroud)

非常有用: https: //javascript.info/selection-range

  • 在 chrome + firefox 和多行上完美运行。最佳解决方案。 (5认同)
  • 仍然可以在 chrome 上使用,谢谢 (2认同)
  • 它也适用于 Firefox。谢谢! (2认同)

am0*_*0wa 10

可以将光标设置到范围的末尾:

setCaretToEnd(target/*: HTMLDivElement*/) {
  const range = document.createRange();
  const sel = window.getSelection();
  range.selectNodeContents(target);
  range.collapse(false);
  sel.removeAllRanges();
  sel.addRange(range);
  target.focus();
  range.detach(); // optimization

  // set scroll to the end if multiline
  target.scrollTop = target.scrollHeight; 
}
Run Code Online (Sandbox Code Playgroud)

  • @Zabs 相当简单:不要每次都调用`setCaretToEnd()` - 仅在需要时调用它:例如在复制粘贴之后,或在限制消息长度之后。 (2认同)

Jua*_*ank 8

如果您不关心较旧的浏览器,那么这个对我来说就是成功的窍门。

// [optional] make sure focus is on the element
yourContentEditableElement.focus();
// select all the content in the element
document.execCommand('selectAll', false, null);
// collapse selection to the end
document.getSelection().collapseToEnd();
Run Code Online (Sandbox Code Playgroud)

  • `document.execCommand` 现已过时 https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand 。 (3认同)

Max*_*lin 5

将光标移动到可编辑范围的末尾以响应焦点事件:

  moveCursorToEnd(el){
    if(el.innerText && document.createRange)
    {
      window.setTimeout(() =>
        {
          let selection = document.getSelection();
          let range = document.createRange();

          range.setStart(el.childNodes[0],el.innerText.length);
          range.collapse(true);
          selection.removeAllRanges();
          selection.addRange(range);
        }
      ,1);
    }
  }
Run Code Online (Sandbox Code Playgroud)

并在事件处理程序中调用它(在此处进行反应):

onFocus={(e) => this.moveCursorToEnd(e.target)}} 
Run Code Online (Sandbox Code Playgroud)


Bob*_*son 5

我知道这个问题已经有了答案,但我认为一句简单的话可能会帮助未来发现这个问题的人:

document.getSelection().modify("move", "forward", "documentboundary");
Run Code Online (Sandbox Code Playgroud)

这将获取当前选定的元素并将光标向前移动(取决于语言 - 向右忽略语言)到文档末尾。

有关如何使用 Selections 执行操作的更多信息,请参阅此处