Summernote - 聚焦,在编辑器末尾插入光标
Summernote - On focus, insert cursor at the end of editor
当 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;
}
});
最初来自这个 post: 然后我修改以与 jQuery 一起工作,特别是针对 Summernote。
当 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;
}
});
最初来自这个 post: 然后我修改以与 jQuery 一起工作,特别是针对 Summernote。