我需要处理网页中选定(用鼠标高亮)的文本。但是,如果我选择有序列表 <ol></ol> 元素,我会失去编号信息。也许有人可以帮助我进行信息提取,因为如果我选择并复制+粘贴选择到文本编辑器中,我会看到那些数字。用于选择html片段的函数如下:
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;
}
}
return html;
}
完整的代码示例请参见:https://jsfiddle.net/t2mhcbyo/3/
<li>
替换为<li> 1. ....
,然后将所有的<ol>
替换为<ul>
。但是你的解决方案更加优雅和灵活。谢谢。 - Ignas