当我替换值时,我的光标移动到我的 contenteditable <p> 的第一个词
My cursor move to the first word of my contenteditable <p> when I replace value
当我输入一个由函数替换的新文本时,我的光标移动到 contenteditable 的开头。我希望我的光标停留在最后一个字母上。
document.designMode = "on";
var text = document.getElementById('text');
let observer = new MutationObserver(mutations =>
mutations.forEach(mutation => {
console.log(text.textContent);
text.textContent = text.textContent.replace('/', ' a');
})
);
observer.observe(text, {
childList: true,
characterData: true,
subtree: true,
});
<p id="text" contenteditable="true">I'm a text will be change</p>
试试这个。
document.designMode = "on";
var text = document.getElementById('text');
let observer = new MutationObserver(mutations =>
mutations.forEach(mutation => {
console.log(text.textContent);
text.textContent = text.textContent.replace('/', ' a');
const range = document.createRange();
const textNode = text.firstChild;
range.setStart(textNode, text.textContent.length);
range.setEnd(textNode, text.textContent.length);
const sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
})
);
observer.observe(text, {
childList: true,
characterData: true,
subtree: true,
});
<p id="text" contenteditable="true">I'm a text will be change</p>
当我输入一个由函数替换的新文本时,我的光标移动到 contenteditable 的开头。我希望我的光标停留在最后一个字母上。
document.designMode = "on";
var text = document.getElementById('text');
let observer = new MutationObserver(mutations =>
mutations.forEach(mutation => {
console.log(text.textContent);
text.textContent = text.textContent.replace('/', ' a');
})
);
observer.observe(text, {
childList: true,
characterData: true,
subtree: true,
});
<p id="text" contenteditable="true">I'm a text will be change</p>
试试这个。
document.designMode = "on";
var text = document.getElementById('text');
let observer = new MutationObserver(mutations =>
mutations.forEach(mutation => {
console.log(text.textContent);
text.textContent = text.textContent.replace('/', ' a');
const range = document.createRange();
const textNode = text.firstChild;
range.setStart(textNode, text.textContent.length);
range.setEnd(textNode, text.textContent.length);
const sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
})
);
observer.observe(text, {
childList: true,
characterData: true,
subtree: true,
});
<p id="text" contenteditable="true">I'm a text will be change</p>