31

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.

I tried this solution, which works for regular textareas, but not for 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.

So, is there a way to accomplish this?

4

4 回答 4

43

你应该使用这个

$.fn.insertAtCaret = function (myValue) {
    myValue = myValue.trim();
    CKEDITOR.instances['idofeditor'].insertText(myValue);
};
于 2012-04-19T08:22:56.520 回答
19

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

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

更多信息在这里

于 2012-04-19T08:18:05.743 回答
4

我想我应该提一下,如果您使用 ckeditor 的 jQuery 适配器,您可以使用 jQuery 插入文本,这样看起来更干净一些。

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

或者如果您要插入 HTML

$('textarea#id_body').ckeditor().editor.insertHtml('<a href="#">text</a>');
于 2014-07-14T16:41:45.590 回答
0

我需要类似的东西。我正在使用 CKEditor 3.6(由于预算)、JQuery 和 Bootstrap。我想要一个按钮列表,当单击 CKeditor 的主体时会插入一些文本。我从我的数据元素创建了一个按钮列表,然后添加了一个点击事件。我的对象是一个带有数据属性的输入按钮,我读取该属性以获取要粘贴的 val。

.insertText("texthere") 将为您提供将值放在光标所在位置所需的操作。

$(function () {
  $(".dataelement").click(function () {
          InsertDataElement($(this).data("valtxt"));
      });
});
function InsertDataElement(valtxt) {
    CKEDITOR.instances['FullDescription'].insertText(valtxt);
}

于 2021-05-07T13:39:06.633 回答