我在 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。如何修改代码以实现此条件?花了几天时间弄清楚这一点,但无济于事。
谢谢。