Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/438.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaScript/HTML:替换输入/contentEditable中的单词->;插入符号向左移动_Javascript_Html_Replace_Caret - Fatal编程技术网

JavaScript/HTML:替换输入/contentEditable中的单词->;插入符号向左移动

JavaScript/HTML:替换输入/contentEditable中的单词->;插入符号向左移动,javascript,html,replace,caret,Javascript,Html,Replace,Caret,我的情况是,我有一个HTML的输入框(现在是一个contentEditable div)元素,我想用一个其他单词替换用户可以输入的一个特定单词: word1 = "hello"; word2 = "<b>hello</b>"; //element = some random element that supports innerHTML element.oninput = function(){ element.innerHTML = element.innerH

我的情况是,我有一个HTML的输入框(现在是一个contentEditable div)
元素
,我想用一个其他单词替换用户可以输入的一个特定单词:

word1 = "hello";
word2 = "<b>hello</b>";
//element = some random element that supports innerHTML
element.oninput = function(){
    element.innerHTML = element.innerHTML.replace(word1, word2);
}
word1=“你好”;
word2=“你好”;
//element=支持innerHTML的一些随机元素
element.oninput=函数(){
element.innerHTML=element.innerHTML.replace(word1,word2);
}
因此,如果用户键入“hello”,它将自动替换为粗体的“hello”,这仅在我使用属性为
innerHTML
的元素时有效,因此我可以插入
。现在我的问题是,一旦innerHTML被替换(l.5),插入符号就会跳回到div中第一个字母的前面:

[这是地狱]->[这是你好]

如果不使用jQuery,我可以做些什么来防止这种情况发生


我还可以更改元素类型/类,它只需要支持
innerHTML

可能的重复。足够接近。我不想使用jQuery。这可能会有帮助:另请参阅:@ScottMarcus由于某些原因它不起作用。可能重复。足够近。我不想使用jQuery。这可能会有所帮助:另请参阅:@ScottMarcus由于某种原因它不起作用。