我需要将插入符号移动到contenteditable
节点的末端,例如在Gmail笔记小部件上。
我阅读了StackOverflow上的线程,但是这些解决方案基于使用输入,并且不适用于contenteditable
元素。
Answers:
还有另一个问题。
该尼科伯恩斯如果的解决方案工作contenteditable
DIV不包含其他元素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: /programming/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: /programming/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元素,在这个问题中,有一些方法可以测试元素是否为void。因此,假设存在一个名为的函数canContainText
,true
如果参数不是void元素,则该函数返回以下代码行:
contentEditableElement.lastChild.tagName.toLowerCase() != 'br'
应替换为:
canContainText(getLastChildElement(contentEditableElement))
编辑#2:上面的代码已完全更新,描述和讨论的每个更改
Uncaught TypeError: Cannot read property 'nodeType' of null
,使用您的函数时出现错误,这是由于调用了getLastChildElement函数引起的。您知道什么可能导致此问题吗?
Geowa4的解决方案适用于文本区域,但不适用于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);
selectNodeContents
的尼科的是给在Chrome和FF我的错误的部分(没有测试其他浏览器),直到我发现我需要的显然要添加.get(0)
的元素,我是喂的功能。我想这与我使用jQuery而不是裸露的JS有关吗?我在问题4233265上从@jwarzech中学到了这一点。谢谢大家!
.get(0)
检索jQuery内部存储的dom元素。您还可以追加[0]
,.get(0)
在此情况下等效。
如果您不关心较旧的浏览器,那么这个对我来说就是成功的窍门。
// [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();
document.execCommand
现在已过时developer.mozilla.org/en-US/docs/Web/API/Document/execCommand。
可以将光标设置到范围的末尾:
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;
}
setCaretToEnd()
每次都调用-仅在需要时调用它:例如在复制粘贴之后或在限制消息长度之后。
响应焦点事件,将光标移到可编辑范围的末尾:
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)}}
最初开始输入时,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>