使用 jQuery 在光标位置插入文本到 CKEditor

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10224075/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 08:58:25  来源:igfitidea点击:

Insert text at the cursor position to a CKEditor using jQuery

jqueryckeditor

提问by Phoenix

I'm trying to add a piece of text to an existing CKEditor using jQuery. This needs to be done when a link is clicked.

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

I tried this solution, which works for regular textareas, but not for CKEditor:

我尝试了这个解决方案,它适用于常规文本区域,但不适用于 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();
      }
    })
  }
});

There is also an option to use: $('#editor').val(), but this appends the text at the end or the beginning and not at the cursor.

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

So, is there a way to accomplish this?

那么,有没有办法做到这一点?

回答by Devjosh

You should use this

你应该用这个

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

回答by Rory McCrossan

CKEditor itself has a mechanism to insert text. If you update the textareadirectly you are in effect bypassing some of the mechanisms CKEditor has to keep track of what text has been entered. Try this:

CKEditor 本身就有插入文本的机制。如果你textarea直接更新你实际上绕过了CKEditor必须跟踪输入的文本的一些机制。尝试这个:

CKEDITOR.instances.IDofEditor.insertText('some text here');

More information here

更多信息在这里

回答by byoungb

I thought I should mention that if you are using the jQuery adapter for ckeditor you can insert text with jQuery this way which looks a little cleaner.

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

$('textarea#id_body').ckeditor().editor.insertText('some text here');

or if you are inserting HTML

或者如果您要插入 HTML

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