使用jQuery将光标位置的文本插入CKEditor

Pho*_*nix 28 jquery ckeditor

我正在尝试使用jQuery向现有的CKEditor添加一段文本.这需要在单击链接时完成.

我试过这个解决方案,适用于常规textareas,但不适用于CKEditor:

jQuery.fn.extend({
  insertAtCaret: function(myValue) {
    return this.each(function(i) {
      if (document.selection) {
        //For browsers like Internet Explorer
        this.focus();
        sel = document.selection.createRange();
        sel.text = myValue;
        this.focus();
      } else if (this.selectionStart || this.selectionStart == '0') {
        //For browsers like Firefox and Webkit based
        var startPos = this.selectionStart;
        var endPos = this.selectionEnd;
        var scrollTop = this.scrollTop;
        this.value = this.value.substring(0, startPos) + myValue + this.value.substring(endPos, this.value.length);
        this.focus();
        this.selectionStart = startPos + myValue.length;
        this.selectionEnd = startPos + myValue.length;
        this.scrollTop = scrollTop;
      } else {
        this.value += myValue;
        this.focus();
      }
    })
  }
});
Run Code Online (Sandbox Code Playgroud)

还有一个选项可以使用:$('#editor').val(),但这会将文本附加到结尾或开头,而不是光标.

那么,有没有办法实现这一目标?

Dev*_*osh 38

你应该用它

$.fn.insertAtCaret = function (myValue) {
    myValue = myValue.trim();
    CKEDITOR.instances['idofeditor'].insertText(myValue);
};
Run Code Online (Sandbox Code Playgroud)

  • 大!谢谢!我做了一个小改动:`CKEDITOR.instances [$(this).attr("id")].insertText(myValue);`所以我不需要担心id. (5认同)

Ror*_*san 17

CKEditor本身有一个插入文本的机制.如果textarea直接更新,则实际上绕过了CKEditor用于跟踪输入文本的一些机制.试试这个:

CKEDITOR.instances.IDofEditor.insertText('some text here');
Run Code Online (Sandbox Code Playgroud)

更多信息在这里


byo*_*ngb 5

我想我应该提一下,如果您使用 ckeditor 的 jQuery 适配器,您可以通过这种方式使用 jQuery 插入文本,这看起来更简洁。

$('textarea#id_body').ckeditor().editor.insertText('some text here');
Run Code Online (Sandbox Code Playgroud)

或者如果您要插入 HTML

$('textarea#id_body').ckeditor().editor.insertHtml('<a href="#">text</a>');
Run Code Online (Sandbox Code Playgroud)