【问题标题】:Summernote - On focus, insert cursor at the end of editorSummernote - 在焦点上,在编辑器末尾插入光标
【发布时间】:2016-05-11 16:36:09
【问题描述】:

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

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

Summernote API 似乎不直接支持这一点,我尝试了各种 hackylooking 解决方案;例如清空文本区域,创建编辑器,然后插入 HTML 节点。光标仍然停留在行首。

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

【问题讨论】:

    标签: javascript cursor-position summernote


    【解决方案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。

    【讨论】:

    • 这段代码应该在jQuery初始化之后调用。例如:$('#FieldToFocus').placeCursorAtEnd();
    • 我尝试在我的example here 中这样做,但我无法让它工作。你能帮我@Mad-Chemist 把它放在哪里吗?
    • @usr4896260 在此处查看我对您的票的回复:stackoverflow.com/a/39706123/2921200
    • @Mad-Chemist,我需要在其中添加此代码以及如何调用该函数?
    • 如果可能,在 jQuery 的 $(document).ready 回调中添加上述代码。您希望上面的代码在 jQuery 初始化后立即执行。一旦发生这种情况,您可以随意调用该方法“$('#FieldToFocus').placeCursorAtEnd();”但在示例中换掉了 jQuery 选择器。
    猜你喜欢
    • 1970-01-01
    • 2019-03-31
    • 1970-01-01
    • 2017-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-22
    相关资源
    最近更新 更多