我需要将插入符号移到contenteditable
节点的末尾,就像在Gmail备注小部件上一样。
我在StackOverflow上读取了线程,但这些解决方案基于使用输入,它们不适用于contenteditable
元素。
答案 0 :(得分:207)
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
}
}
它可以被类似的代码使用:
elem = document.getElementById('txt1');//This is the element that you want to move the caret to the end of
setEndOfContenteditable(elem);
答案 1 :(得分:22)
还有另一个问题。
如果contenteditable
div不包含其他多行元素,则Nico Burns的解决方案有效。
例如,如果一个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 ,在this question中有一些方法可以测试元素是否为void。因此,假设存在一个名为canContainText
的函数,如果参数不是void元素,则返回true
,代码如下:
contentEditableElement.lastChild.tagName.toLowerCase() != 'br'
应替换为:
canContainText(getLastChildElement(contentEditableElement))
编辑#2 :上述代码已完全更新,并描述和讨论了所有更改
答案 2 :(得分:3)
可以通过范围将光标设置到最后:
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;
}
答案 3 :(得分:1)
如果您不关心较旧的浏览器,那么这个就对我有用。
// [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();
答案 4 :(得分:0)
我在尝试使元素可编辑时遇到类似的问题。在Chrome和FireFox中可能出现这种情况,但在FireFox中,插入号要么移至输入的开头,要么移至输入结束后的一个空格。我认为最终用户在尝试编辑内容时非常困惑。
我找不到尝试几种方法的解决方案。唯一对我有用的方法是,通过在我的我的内部放置普通的旧文本输入来“解决问题”。现在可以了。似乎“内容可编辑”仍然是最前沿的技术,取决于上下文,该技术可能会或可能不会像您希望的那样起作用。
答案 5 :(得分:0)
将光标移动到可编辑跨度的末尾以响应焦点事件:
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);
}
}
并在事件处理程序中调用它(在此处反应):
onFocus={(e) => this.moveCursorToEnd(e.target)}}
答案 6 :(得分:0)
最初开始输入时,contenteditable
<div>
和<span>
的问题已解决。一种解决方法是在div元素和该函数上触发焦点事件,清除并重新填充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>