当 Summernote 文本编辑器初始化并将 focus
属性设置为 true
时,编辑器获得焦点但将光标置于编辑器的开头。
我的偏好是将光标放置在用户最初单击的位置。至少我只需要将光标放在编辑器的末尾。
Summernote API 似乎并不直接支持这一点,我已经尝试了各种看起来很老套的解决方案;比如清空文本区域,创建编辑器,然后插入 HTML 节点。光标仍停留在行首。
忘记包括我的 fiddle :http://jsfiddle.net/madChemist/gvy3po4L/1/
最佳答案
这是我修改后适合我的解决方案:
$.fn.extend({
placeCursorAtEnd: function() {
// Places the cursor at the end of a contenteditable container (should also work for textarea / input)
if (this.length === 0) {
throw new Error("Cannot manipulate an element if there is no element!");
}
var el = this[0];
var range = document.createRange();
var sel = window.getSelection();
var childLength = el.childNodes.length;
if (childLength > 0) {
var lastNode = el.childNodes[childLength - 1];
var lastNodeChildren = lastNode.childNodes.length;
range.setStart(lastNode, lastNodeChildren);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
return this;
}
});
最初来自这篇文章:https://stackoverflow.com/a/6249440/2921200然后我修改以使用 jQuery 并专门针对 Summernote。
关于javascript - Summernote - 聚焦,在编辑器末尾插入光标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35160816/