2

我在 SE 的某个地方发现了一个代码,用于在 Tim Down 的 contenteditable 中插入文本。代码如下所示,并且运行良好。但是我想添加一个基于我的要求的条件,并且想以某种方式修改代码,但经过这么多试验后未能做到。

function insertTextAtCursor(value, stepback) {
    var sel, range, textNode;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            range = sel.getRangeAt(0);         
            textNode = document.createTextNode(value);


           //Check value of stepback: 0 or 1
            if(!stepback)//if 0
                 range.insertNode(textNode);
            if(stepback){ //if 1
               // replace the previously inserted character with the new one here

            }

            // Move caret to the end of the newly inserted text node   
            range.setStart(textNode, textNode.length);
            range.setEnd(textNode, textNode.length);

            sel.removeAllRanges();
            sel.addRange(range);          

        }
    } else if (document.selection && document.selection.createRange) {
        range = document.selection.createRange();
        range.pasteHTML(text);
    }
}

在这里,我正在检查stepback参数的值,即 0 或 1。如果为 0,则将插入按下的字符,但如果为 1,我想用新字符替换最后一个字符。在我的例子中,当一个键被按下后紧跟一个元音(例如,按下 m 后跟一个)时,后退返回 1。如何修改代码以实现此条件?花了几天时间弄清楚这一点,但无济于事。

谢谢。

4

1 回答 1

4

代替以下内容:

//Check value of stepback: 0 or 1
if(!stepback)//if 0
     range.insertNode(textNode);
if(stepback){ //if 1
   // replace the previously inserted character with the new one here

}

使用以下代码:

// This clones the selected range and then selects 1
// 1 character in the backward direction and deletes it.
if(stepback){
    clone = range.cloneRange();
    clone.setStart(range.startContainer, range.startOffset - 1);
    clone.setEnd(range.startContainer, range.startOffset);
    clone.deleteContents();
}
range.insertNode(textNode);

这确保了总是在末尾添加新的翻译字符,同时在需要后退的情况下可选地删除 1 个字符。

更新:我仅在 Chromium 中对此进行了测试。

于 2013-11-15T09:03:57.233 回答