我需要contenteditable像 Gmail 笔记小部件一样将插入符号移动到节点的末尾。
我在 StackOverflow 上阅读了线程,但这些解决方案基于使用输入,并且它们不适用于contenteditable元素。
我需要contenteditable像 Gmail 笔记小部件一样将插入符号移动到节点的末尾。
我在 StackOverflow 上阅读了线程,但这些解决方案基于使用输入,并且它们不适用于contenteditable元素。
Geowa4 的解决方案适用于 textarea,但不适用于 contenteditable 元素。
此解决方案用于将插入符号移动到 contenteditable 元素的末尾。它应该适用于所有支持 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
    }
}
它可以被类似的代码使用:
elem = document.getElementById('txt1');//This is the element that you want to move the caret to the end of
setEndOfContenteditable(elem);
如果你不关心旧的浏览器,这个对我有用。
// [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();
还有另一个问题。
该尼科伯恩斯如果的解决方案工作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 || {}));
用法:
var editableDiv = document.getElementById("my_contentEditableDiv");
cursorManager.setEndOfContenteditable(editableDiv);
这样,光标肯定定位在最后一个元素的末尾,最终嵌套。
编辑 #1:为了更通用,while 语句还应考虑所有其他不能包含文本的标签。这些元素被命名为void elements,在这个问题中有一些关于如何测试元素是否为空的方法。因此,假设存在一个调用的函数canContainText,true如果参数不是空元素,则返回该函数,以下代码行:
contentEditableElement.lastChild.tagName.toLowerCase() != 'br'
应替换为:
canContainText(getLastChildElement(contentEditableElement))
编辑#2:上面的代码已经完全更新,描述和讨论了每一个变化
可以将光标设置到范围的末尾:
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; 
}
将光标移动到可编辑范围的末尾以响应焦点事件:
  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);
    }
  }
并在事件处理程序中调用它(在这里react):
onFocus={(e) => this.moveCursorToEnd(e.target)}}