2
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;
}
我使用的是上面提供的代码:How to get selected html text with javascript?。获取HTML选择
但是,实际的html和函数返回的html存在如此不一致的地方。例如,假设下面的HTML:
<div>
<p><b>The quick brown fox jumps over the lazy <a href="www.google.com">dog</a></b></p>
<img src="http://www.fakingnews.firstpost.com/wp-content/uploads/2015/12/kim-jaya.jpg" alt="Smiley face" height="42" width="42">
<hr>
<p>The quick brown fox jumps over the lazy <a href="http://www.google.com">dog</a></p>
<li>
<ul>1</ul>
<ul>2</ul>
<ul>3</ul>
<ul>4</ul>
<ul>5</ul>
</li>
</div>
<br />
<input id="showSelected" type="button" value="showSelected" />
如果我选择
x jumps over the lazy <a href="http://www.google.com">dog</a></p>
<li>
<ul>1</ul>
<ul>2</ul>
<ul>3</ul>
函数实际上返回
<div><p>x jumps over the lazy <a href="http://www.google.com">dog</a></p>
<li>
<ul>1</ul>
<ul>2</ul>
<ul>3</ul>
<ul>4</ul>
<ul>5</ul>
</li>
</div>
我注意到,在前面的额外的标记出现当我也选择一个列表,但我确定还有其他不一致的情况。有什么我可以做得到一个确切的HTML副本?