使用jQuery在光标位置将文本插入CKEditor [英] Insert text at the cursor position to a CKEditor using jQuery

查看:431
本文介绍了使用jQuery在光标位置将文本插入CKEditor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用jQuery添加一个文本到现有的CKEditor。
这个需要在点击链接时完成。

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.

我试过这个解决方案,它适用于普通textareas,但不适用于CKEditor:

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();
      }
    })
  }
});

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

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.


推荐答案

您应该使用

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

这篇关于使用jQuery在光标位置将文本插入CKEditor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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