在CKEditor中获得插入符的位置 [英] Get caret position in a CKEditor

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

问题描述

我的模板中有一个CKEditor(不幸的是,我没有决定在此模板上使用其他东西),我需要在当前插入符号位置的主体中的现有文本中插入一个预定的字符串.我找不到找到该职位的好方法,而且对此问题的任何其他支持都很少.

I have a CKEditor in my template (unfortunately it is not my decision to use something else over this) of which I need to insert a pre-determined string into the existing text in the body at the current caret position. I cannot find a good way to obtain the position and any other support for this issue is scarce.

有人知道这样做的可能性吗?

Does anyone know a way this this is possible?

组件

template = new Template() // eventually gets set
@ViewChild("cke-editor-name") editor: ElementRef;
insertText(string) {
    var caretPos = ???;
    template.BodyHtml = template.BodyHtml.substr(0, caretPos) + string + template.BodyHtml.substr(caretPos, string.length());
}

推荐答案

最后找到了一种在每个浏览器上都对我有效的方法.

Finally found a way that works well for me on every browser.

getCaretPos(){
    let sel = window.getSelection();
    let range;
    if (typeof document.caretPositionFromPoint !== "undefined") {
      var e = sel
        .getRangeAt(0)
        .cloneRange()
        .getBoundingClientRect()[0];
      range = document.caretPositionFromPoint(e.clientX, e.clientY);
    } else if (sel && sel.rangeCount > 0) {
      range = sel.getRangeAt(0);
    }
    if (!range) return;
    var caretPos = range.startOffset;
    return caretPos;
}

这篇关于在CKEditor中获得插入符的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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