Tinymce-是否可以获得与所见即所得编辑器相对应的文本区域的插入位置?

use*_*156 5 javascript wysiwyg position tinymce caret

我想知道,当假光标位于“所见即所得”编辑器中的某个位置时,我们能否获得textarea的真实插入符位置?

为了更好地理解问题,请参见下图

在此处输入图片说明 在所见即所得模式下,当光标在s之后时,我们得到位置53。当光标在t之后时,我们得到位置79

该代码将类似于...

function getRealCaretPosition() {
    // all the dirty work goes here
}

// Ctrl + Q
if(e.ctrlKey && e.which == 81) {
    var pos = getRealCaretPosition();
    alert(pos);
}
Run Code Online (Sandbox Code Playgroud)

从理论上讲,这有可能实现吗?

Pau*_* S. 2

window.getSelection()将为您提供当前选择点,然后从这里向后树形行走直到节点的开头,添加遇到的所有文本节点的长度。

function walkback(node, stopAt) {
    if (node.childNodes && node.childNodes.length) { // go to last child
        while (node && node.childNodes.length > 0) {
            node = node.childNodes[node.childNodes.length - 1];
        }
    } else if (node.previousSibling) { // else go to previous node
        node = node.previousSibling;
    } else if (node.parentNode) { // else go to previous branch
        while (node && !node.previousSibling && node.parentNode) {
            node = node.parentNode;
        }
        if (node === stopAt) return;
        node = node.previousSibling;
    } else { // nowhere to go
        return;
    }
    if (node) {
        if (node.nodeType === 3) return node;
        if (node === stopAt) return;
        return walkback(node, stopAt);
    }
    return;
}

function getRealCaretPosition() {
    var sel = window.getSelection(), // current selection
        pos = sel.anchorOffset, // get caret start position
        node = sel.anchorNode; // get the current #text node
    while (node = walkback(node, myContentEditableElement)) {
        pos = pos + node.data.length; // add the lengths of the previous text nodes
    }
    return pos;
}
Run Code Online (Sandbox Code Playgroud)

当然,您还需要检查当前选择是否确实也在您感兴趣的HTMLElement内。