Javascript 替换 contenteditable div 中的选定文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3997659/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
replace selected text in contenteditable div
提问by Judy
I have been looking high and low for an answer but failed.
我一直在寻找答案,但失败了。
Is there a cross-browser solution to replace selected text in contenteditable div? I simply want users to highlight some text and replace the highlighted text into xxxxx.
是否有跨浏览器解决方案来替换 contenteditable div 中的选定文本?我只是希望用户突出显示某些文本并将突出显示的文本替换为 xxxxx。
回答by Tim Down
The following will do the job in all the major browsers:
以下将在所有主要浏览器中完成这项工作:
function replaceSelectedText(replacementText) {
var sel, range;
if (window.getSelection) {
sel = window.getSelection();
if (sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
range.insertNode(document.createTextNode(replacementText));
}
} else if (document.selection && document.selection.createRange) {
range = document.selection.createRange();
range.text = replacementText;
}
}