How to move cursor to end of contenteditable entity

我需要移动插入符号到结束的 contenteditable节点像在 Gmail 备注小部件。

我读过 StackOverflow 上的线程,但是那些解决方案是基于使用输入的,并且它们不能与 contenteditable元素一起工作。

72593 次浏览

Geowa4的解决方案适用于 texttarea,但不适用于 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);

还有一个问题。

如果 contenteditable div 不包含其他多行元素,则 Nico Burns的解决方案可以工作。

例如,如果一个 div 包含其他 div,而这些 div 包含其他内容,就可能发生一些问题。

为了解决这些问题,我安排了以下的解决方案,这是对 尼科的一个改进:

//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。因此,假设存在一个名为 canContainText的函数,如果参数不是 void 元素,该函数返回 true,下面的代码行:

contentEditableElement.lastChild.tagName.toLowerCase() != 'br'

should be replaced with:

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

我在尝试使元素可编辑时遇到了类似的问题。这在 Chrome 和 FireFox 中是可能的,但在 FireFox 中,插入符号要么指向输入的开头,要么指向输入结束后的一个空格。我认为,试图编辑内容的最终用户会感到非常困惑。

我试了好几种方法都没有找到解决的办法。对我来说唯一有效的方法就是“绕过这个问题”,将一个普通的旧文本输入放在我的。现在成功了。似乎“内容可编辑”仍然是前沿技术,这可能会或可能不会按照您希望它工作,这取决于上下文。

根据焦点事件将光标移动到可编辑跨度的末尾:

  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 here) :

onFocus={(e) => this.moveCursorToEnd(e.target)}}

如果你不关心旧的浏览器,这个为我做了技巧。

// [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();

contenteditable <div><span>的问题在最初开始键入时得到解决。解决这个问题的一个方法是在 div 元素和该函数上触发一个焦点事件,clear 并重新填充 div 元素中已经存在的内容。这样问题就解决了,最后您可以使用范围和选择将光标放在末尾。对我有用。

  moveCursorToEnd(e : any) {
let placeholderText = e.target.innerText;
e.target.innerText = '';
e.target.innerText = placeholderText;


if(e.target.innerText && document.createRange)
{
let range = document.createRange();
let selection = window.getSelection();
range.selectNodeContents(e.target);
range.setStart(e.target.firstChild,e.target.innerText.length);
range.setEnd(e.target.firstChild,e.target.innerText.length);
selection.removeAllRanges();
selection.addRange(range);
}
}

在 HTML 代码中:

<div contentEditable="true" (focus)="moveCursorToEnd($event)"></div>

只使用 selection(没有 range)的更短和可读的版本:

function setEndOfContenteditable(elem) {
let sel = window.getSelection();
sel.selectAllChildren(elem);
sel.collapseToEnd();
}
<p id="pdemo" contenteditable>
A paragraph <span id="txt1" style="background-color: #0903">span text node <i>span italic</i></span> a paragraph.
<p>


<button onclick="pdemo.focus(); setEndOfContenteditable(txt1)">set caret</button>

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