【发布时间】:2023-03-21 05:52:01
【问题描述】:
我想选择用户在 contenteditable div 中选择的任何内容的 HTML。我找到了一些代码来检索所选内容的 HTML,但它不仅限于 div。
我想要做的是复制选定的 HTML,将标签包裹在它周围,然后用它替换选择。因此,例如,'test' 会变成 'test'。
<div contenteditable="true" class="body" id="bodydiv"></div>
function getSelectionHtml() {
var html = "";
if (typeof window.getSelection != "undefined") {
var sel = window.getSelection();
if (sel.rangeCount) {
var container = document.createElement("div");
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
container.appendChild(sel.getRangeAt(i).cloneContents());
}
html = container.innerHTML;
}
} else if (typeof document.selection != "undefined") {
if (document.selection.type == "Text") {
html = document.selection.createRange().htmlText;
}
}
}
【问题讨论】:
-
感谢您的回复。我已经看到了。唯一的问题是它适用于您选择的任何文本,包括 div 之外的内容。
标签: javascript html getselection