将插入符号位置移动到ContentEditable<DIV>

Move caret position after focus() for ContentEditable <DIV>

本文关键字:lt DIV gt ContentEditable 插入 符号 位置 移动      更新时间:2023-09-26

我正试图用JavaScript创建一个非常基本的富文本编辑器,但我在选择方面遇到了问题。所以基本上,因为它是一个contentEditable<div>,每当用户从网页粘贴预先格式化的文本时,格式不会被剥离。

一个容易破解的破解方法是将焦点放在<text区域>当按下Ctrl+V时,文本被粘贴到那里,然后在向上键时,将焦点放回<div>,复制内容并删除进入<text区域>。

所以这很容易,但当我把焦点放回内容Editable&;t;div>,插入符号的位置在粘贴的开头,而不是紧接在粘贴之后。我对选择和其他事情了解不够,所以我很感激你的帮助。这是我的代码:

// Helpers to keep track of the length of the thing we paste, the cursor position
// and a temporary random number so we can mark the position.
editor_stuff = 
{
    cursor_position: 0,
    paste_length: 0,
    temp_rand: 0,
}
// On key up (for the textarea).
document.getElementById("backup_editor").onkeyup = function() 
{ 
    var main_editor     =  document.getElementById("question_editor");
    var backup_editor   =  document.getElementById("backup_editor");
    var marker_position = main_editor.innerHTML.search(editor_stuff.temp_rand);
    // Replace the "marker" with the .value of the <textarea>
    main_editor.innerHTML = main_editor.innerHTML.replace(editor_stuff.temp_rand, backup_editor.value);
    backup_editor.value = "";
    main_editor.focus();
}
// On key down (for the contentEditable DIV).
document.getElementById("question_editor").onkeydown = function(event)
{
    key = event;
    // Grab control + V end handle paste so "plain text" is pasted and
    // not formatted text. This is easy to break with Edit -> Paste or
    // Right click -> Paste.
    if
    (
        (key.keyCode == 86 || key.charCode == 86) &&                   // "V".
        (key.keyCode == 17 || key.charCode == 17 || key.ctrlKey)       // "Ctrl"
    )
    {
        // Create a random number marker at the place where we paste.
        editor_stuff.temp_rand = Math.floor((Math.random() * 99999999));
        document.getElementById("question_editor").textContent +=  editor_stuff.temp_rand;
        document.getElementById("backup_editor").focus();
    }
}

因此,我的想法是将光标位置(整数)存储在助手数组(editor_stuff.cursor_position)中。

注意:我一整天都在SO上寻找其他答案,但都找不到。

这里有一个在插入符号位置插入文本的函数:

演示:http://jsfiddle.net/timdown/Yuft3/2/

代码:

function pasteTextAtCaret(text) {
    var sel, range;
    if (window.getSelection) {
        // IE9 and non-IE
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            range = sel.getRangeAt(0);
            range.deleteContents();
            var textNode = document.createTextNode(text);
            range.insertNode(textNode);
            // Preserve the selection
            range = range.cloneRange();
            range.setStartAfter(textNode);
            range.collapse(true);
            sel.removeAllRanges();
            sel.addRange(range);
        }
    } else if (document.selection && document.selection.type != "Control") {
        // IE < 9
        document.selection.createRange().text = text;
    }
}