用户在contenteditable div中键入时替换最后一个字符 [英] Replace last character while user typing in contenteditable div
问题描述
我在SE中的某个地方找到了一个代码,用于在Tim Down可编辑的内容中插入文本。该代码如下所示,并且运行良好。但是我想添加一个基于我的要求的条件,并想以某种方式修改代码,但经过如此多次的尝试却未能做到。
I found, somewhere in SE, a code to insert text in contenteditable by Tim Down. The code looks like the following and is working perfect. But I want to add a condition that is based on my requirement and wanted to modify the code somehow but failed to do it after so many trials.
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再按下a)时,后退将返回1。如何修改代码以达到此条件?花了几天的时间来解决这个问题,但无济于事。
Here I am checking the value of the stepback parameter which is 0 or 1. If 0 then the pressed character will be inserted but if 1 I want to replace the last character with the new one. In my case, the stepback returns 1 when a key is pressed immediately followed by a vowel (for instance, pressing m followed by a). How can I modify the code to achieve this condition? Spent days to figure out this but to no avail.
谢谢。
推荐答案
代替以下内容:
//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个字符
This ensures that the new translated character is always added at the end while optionally removing the 1 character in case stepback is required.
更新:我仅在Chromium中对此进行了测试。
UPDATE: I have tested this in Chromium only.
这篇关于用户在contenteditable div中键入时替换最后一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!