是否可以替换所选文本并保留HTML(跨选定文本)?
我想在按钮单击时将文本设置为Upper或Lower,并将html标记范围保留在所选文本中。我的代码看起来像这样。
function replaceSelectedText(replacementText) {
var sel, range;
var selectedText=window.getSelection().toString();
// Pokud je oznaceny text a je obsazen v divu 'zprava'
if ($.trim(selectedText)!="") {
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;
}
}
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p contenteditable>DJSH SAJKDH ASDK ahsjkda sdasd <span style="color:red">asjda lsdjkl LASJD ASLdkja sdlASdjk aůskjd aůSdkj asdů</span></p>
<button type="button" class="btn btn-default" onclick="replaceSelectedText(window.getSelection().toString().toLowerCase());">a↓</button>
<button type="button" class="btn btn-default" onclick="replaceSelectedText(window.getSelection().toString().toUpperCase());">A↑</button>
&#13;