简体   繁体   English

在ContentEditable的focus()之后移动插入符号的位置<DIV>

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

I am trying to create a very basic rich-text editor in JavaScript but I'm having an issue with selections. 我正在尝试用JavaScript创建一个非常基本的RTF编辑器,但是选择时遇到了问题。 So basically, since it's a contentEditable <div>, any time the user pastes in pre-formatted text from a webpage, the formatting doesn't get stripped off. 因此,基本上,由于它是一个contentEditable <div>,因此每当用户从网页粘贴预先格式化的文本时,该格式就不会被剥夺。

An easy to break hack is to give focus to a <textarea> upon Ctrl + V being pressed, so the text gets pasted in there, then onkeyup, give focus back to the <div>, copy the contents over and delete whatever went in to the <textarea>. 一个容易破解的技巧是在按下Ctrl + V时将焦点放在<textarea>上,以便将文本粘贴到其中,然后onkeyup,将焦点返回到<div>,将内容复制过来并删除输入的内容到<textarea>。

So that's easy, but when I give focus back to the contentEditable &;t;div>, the caret position is at the beginning and not immediately after the paste. 这样很容易,但是当我将焦点放回到contentEditable&; t; div>上时,插入标记的位置在开始处,而不是紧接在粘贴之后。 I don't know enough about selections and whatnot to figure it out, so I'd appreciate some help. 我对选择知识不甚了解,无法弄清楚,因此,我希望获得一些帮助。 Here's my code: 这是我的代码:

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

So my thinking is to store the cursor position (integer) in my helper array ( editor_stuff.cursor_position ). 所以我的想法是将光标位置(整数)存储在我的助手数组( editor_stuff.cursor_position )中。

NB I've been looking at other answers on SO all day and can't get any of them to work for me. 注意:我整天都在寻找其他答案,因此无法为我工作。

Here's a function that inserts text at the caret position: 这是一个在插入符号位置插入文本的函数:

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

Code: 码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM