我想在contenteditable
div中替换光标前的单词(另请参阅Detect the last written word when typing TAB in a textarea or contenteditable div)。
以下代码:
contenteditable
div 不适用于contenteditable
div的下一段:
Uncaught IndexSizeError:无法在'Range'上执行'setStart':偏移量71大于节点的长度(38)。
在contenteditable
div的第二行按TAB时,如何修改以下代码才能使其正常工作?
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>
注意:我已经测试了Replace specific word in contenteditable的答案,但是当contenteditable div中有多行时它不起作用。
答案 0 :(得分:4)
这有效:
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();
}
}
});
&#13;
<div contenteditable>Hello, press TAB to replace this WORD<br>Also press TAB after this ONE</div>
&#13;
textarea
和div
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !\.[^\/]+$
RewriteRule ^(.*?)/?$ /index.php?p=$1 [L,QSA]
这是full solution。