Summernote - 在焦点上,将光标插入编辑器的末尾 [英] Summernote - On focus, insert cursor at the end of editor

查看:727
本文介绍了Summernote - 在焦点上,将光标插入编辑器的末尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当Summernote文本编辑器初始化并将焦点属性设置为 true 时,编辑器会获得焦点但放置光标位于编辑器的开头。

When the Summernote text editor initializes with the focus property set to true, the editor gains focus but places the cursor at the beginning of the editor.

我的偏好是将光标放在用户最初点击的位置。至少我只需要将光标放在编辑器的末尾。

My preference would be to have the cursor placed where the user had clicked initially. At a bare minimum I would just need to place the cursor at the end of the editor.

Summernote API似乎没有直接支持这个,我试过了各种 hacky looking 解决方案;如清空文本区域,创建编辑器,然后插入HTML节点。光标仍然在行的开头。

The Summernote API doesn't seem to directly support this and I've tried various hacky looking solutions; Such as emptying the text area, creating the editor, then inserting the HTML nodes. The cursor remains at the beginning of the line still.

忘了包括我的小提琴: http://jsfiddle.net/madChemist/gvy3po4L/1/

Forgot to include my fiddle: http://jsfiddle.net/madChemist/gvy3po4L/1/

推荐答案

以下是我修改为我工作的解决方案:

Here is the solution I've modified to work for me:

        $.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。

Which originally came from this post: https://stackoverflow.com/a/6249440/2921200 and then I modified to work with jQuery & specifically against Summernote.

这篇关于Summernote - 在焦点上,将光标插入编辑器的末尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆