问题描述
我想替换 contenteditable
div中的光标前的单词(另请参阅,但当contenteditable div中有多行时它不起作用。
此作品:
$ b
这是,适用于 textarea
和contenteditable div
。
I want to replace the word before cursor in contenteditable
div (see also Detect the last written word when typing TAB in a textarea or contenteditable div).
The following code:
- totally works for the first paragraph of the
contenteditable
div does not work for the next paragraphs of the
contenteditable
div:
How should I modify the following code to make it work when pressing TAB in the 2nd line of the contenteditable
div?
document.addEventListener("keydown", function(e) {
var elt = e.target;
if (elt.isContentEditable)
{
if (e.keyCode == 9) {
e.preventDefault();
elt.focus();
range = document.getSelection().getRangeAt(0).cloneRange();
range.collapse(true);
range.setStart(elt, 0);
var words = range.toString().trim().split(' ');
var lastWord = words[words.length - 1];
if (lastWord) {
var wordStart = range.toString().lastIndexOf(lastWord);
var wordEnd = wordStart + lastWord.length;
range.setStart(elt.firstChild, wordStart);
range.setEnd(elt.firstChild, wordEnd);
range.deleteContents();
document.execCommand('insertText', false, "hello\nnewline");
elt.normalize();
}
}
}
});
<div contenteditable>Hello, click here and press TAB to replace this WORD<br>Also click here and press TAB after this ONE</div>
Note: I've already tested the answer from Replace specific word in contenteditable but it doesn't work when there are multiple lines in the contenteditable div.
This works:
document.addEventListener("keydown", function(e) {
var elt = e.target;
if (elt.isContentEditable)
{
if (e.keyCode == 9) {
e.preventDefault();
elt.focus();
sel = document.getSelection();
sel.modify("extend", "backward", "word");
range = sel.getRangeAt(0);
console.log(range.toString().trim());
range.deleteContents();
var el = document.createElement("div");
el.innerHTML = '<b>test</b> and a <a href="hjkh">link</a>';
var frag = document.createDocumentFragment(), node;
while (node = el.firstChild) {
frag.appendChild(node);
}
range.insertNode(frag);
range.collapse();
}
}
});
<div contenteditable>Hello, press TAB to replace this WORD<br>Also press TAB after this ONE</div>
This is a full solution for both textarea
and contenteditable div
.
这篇关于在游标之前替换单词时,在contenteditable中有多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!