簡體   English   中英

Tinymce - 是否有可能獲得與所見即所得編輯器對應的textarea的插入位置?

[英]Tinymce - Is it possible to get caret position of textarea corresponding to WYSIWYG Editor?

我想知道當假冒光標在WYSIWYG編輯器下處於某個位置時,我們是否可以獲得textarea的真實插入位置?

為了更好地理解這個問題,請參見下圖

在此輸入圖像描述 在WYSIWYG模式下,當光標在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);
}

從理論上講,這有可能實現嗎?

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

當然,您還需要檢查當前選擇是否在您感興趣的HTMLElement中。

是的,tinyMCE上有一個主題說明了這一點:

var inst = getInstanceById('editor/elementid');
var myBookmark = inst.getBookmark();

// do something, move the cursor position
inst.moveToBookmark(myBookmark);

來源 :從這里檢查其他解決方案,如果這些不起作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM