将光标设置在可编辑内容的末尾
Set cursor at the end of content editable
我有一个简单的可编辑内容,其中包含带标记的文本。。。当一个标签被插入时,单词会被里面的跨度替换…
<div contenteditable=true>
text text text <span class="tag">tag</span>
</div>
这就是结果(当用户按下空格键时,标签会被一个包含标签文本的跨度所取代;这种情况发生在按键上)
然后我需要将光标放在可编辑内容的末尾(范围外),以便用户继续键入。。。
我已经可以在末尾移动光标,但只能在范围内移动。。。
我用瘦腿。
这可能适用于
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);
}
这也简单得多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
}
}
相关文章:
- 内容可编辑分区-根据内部HTML位置的光标位置
- Javascript/jQuery在可编辑的DIV中设置光标
- 无法在 NG 网格中行的编辑字段中移动光标
- 为什么触发点击内容可编辑不会激活元素和设置光标
- ContentEditable元素--将光标移回可编辑文本的开头
- 如何在实时编辑器中跟踪带有名称的用户光标
- 如何从内容可编辑区域获取光标位置之前的文本
- 将光标设置在可编辑内容的末尾
- 如何在Wysihtml5沙盒编辑器中的光标位置插入文本
- 如何将光标放在 MathQuill (0.10) 字段,以便可以键入以立即进行编辑
- 在拖动/拖放事件上获取 Firefox 内容可编辑的拖放光标位置
- 将图片拖放到 Chrome 中可编辑的内容光标处
- 防止内容可编辑在光标处设置文本样式
- 在 Ace 编辑器中的多个光标上执行方法
- IE9 内容可编辑中显示错误的光标
- Javascript html 编辑器光标焦点跟随鼠标
- 当使用css after时,嵌套内容可编辑结构中的chrome中没有出现光标
- 编辑光标未显示在 Chrome 上的内容可编辑中
- javascript内容可编辑:将光标设置为字符偏移量
- 如何在wysiwyg编辑器中按需隐藏光标闪烁符(插入符号)?(redector.js)