Javascript 获取HTML选择 函数getSelectionHtml(){ var html=“”; if(typeof window.getSelection!=“未定义”){ var sel=window.getSelection(); 如果(选择范围计数){ var container=document.createElement(“div”); 对于(变量i=0,len=sel.rangeCount;i

Javascript 获取HTML选择 函数getSelectionHtml(){ var html=“”; if(typeof window.getSelection!=“未定义”){ var sel=window.getSelection(); 如果(选择范围计数){ var container=document.createElement(“div”); 对于(变量i=0,len=sel.rangeCount;i,javascript,html,Javascript,Html,我正在使用上面提供的代码: 但是,实际的html和函数返回的html之间存在很多不一致之处。例如,给定以下html: function getSelectionHtml() { var html = ""; if (typeof window.getSelection != "undefined") { var sel = window.getSelection(); if (sel.rangeCount) { var co

我正在使用上面提供的代码:

但是,实际的html和函数返回的html之间存在很多不一致之处。例如,给定以下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;
}

敏捷的棕色狐狸跳过懒惰的狐狸


敏捷的棕色狐狸跳过懒惰的狐狸

    • 1
      2
      3
      4
      5

  • 如果我要选择

    <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跳过懒惰的人

    • 1
      2
      3
  • 函数实际返回

    x jumps over the lazy <a href="http://www.google.com">dog</a></p>
    <li>
        <ul>1</ul>
        <ul>2</ul>
        <ul>3</ul>
    
    x跳过懒惰的

    • 1
      2
      3
      4
      5

  • 我注意到,当我同时选择一个列表时,前面会出现额外的标记,但我确信还有其他不一致的情况。我可以做些什么来获得准确的HTML副本吗?

    因为您选择的不是有效的HTML,例如缺少开始和结束标记,所以您在问题中列出的代码无法按预期工作, 在您的情况下,您需要使用文本选择功能,类似于:

    <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>
    
    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;
    }