Cer*_*ler 3 javascript contenteditable rangy
我有一个简单的可编辑内容,其中包含带有标签的文本...当插入标签时,单词将替换为其中的跨度...
<div contenteditable=true>
text text text <span class="tag">tag</span>
</div>
Run Code Online (Sandbox Code Playgroud)
这就是结果(当用户按空格键时,标签被包含标签文本的跨度替换;这在键入时发生)
然后,我需要将光标放在可编辑内容的末尾(跨度之外),以便让用户继续输入...
我已经能够将光标移动到最后,但只能移动到跨度内...
我用兰吉。
小智 6
这可能有效
function moveCursorAtTheEnd(){
var selection=document.getSelection();
var range=document.createRange();
var contenteditable=document.querySelector('div[contenteditable="true"]');
if(contenteditable.lastChild.nodeType==3){
range.setStart(contenteditable.lastChild,contenteditable.lastChild.length);
}else{
range.setStart(contenteditable,contenteditable.childNodes.length);
}
selection.removeAllRanges();
selection.addRange(range);
}
Run Code Online (Sandbox Code Playgroud)
sk8*_* ツ 5
这也更简单https://gist.github.com/al3x-edge/1010364
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)