获取HTML选择

时间:2017-02-12 20:35:22

标签: javascript 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;
}

我正在使用上面提供的代码:How to get selected html text with javascript?

然而,与函数返回的实际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副本吗?

1 个答案:

答案 0 :(得分:1)

由于您选择的内容不是有效的HTML,例如缺少开始和结束标记,因此您在问题中列出的代码无法按预期工作, 在您的情况下,您需要使用文本选择功能,如:https://stackoverflow.com/a/169873/200713

function getSelectedText() {
  var txt = '';

  if (window.getSelection) {
    txt = window.getSelection();
  }
  else if (document.getSelection) {
    txt = document.getSelection();
  }
  else if (document.selection) {
    txt = document.selection.createRange().text;
  }
  else return; 

  return txt;
}