window.getSelection包含HTML标记

时间:2018-10-03 15:44:37

标签: javascript

说html页面包含此行

head<div class='myClass'>select me</div>tail

它在页面上显示为headselect metail,

var sel = window.getSelection ? window.getSelection() : document.selection.createRange();
var html = "";
                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;
                }
console.log(html);

当用户选择“选择我”时, 以下代码返回

select me

当用户选择“ dselect met”时, 然后代码返回

d<div class='myClass">select me</div>t

如何通过仅选择“选择我”来返回<div class='myClass">select me</div>

在不影响原始文本选择的情况下,例如选择“再次选择”

<p>this select again with no HTML tag</p>

document.selection.createRange()呢?对于IE

1 个答案:

答案 0 :(得分:0)

欢迎光临!您尝试做的事情是可能的,但可能并不总是表现出您想要的方式。我已经附上了一个示例,但是基本上您希望查看选择的第一个和最后一个节点。如果它们相同(即您的选择全部在同一个节点内),则可以查看所选内容是否与该节点的全部内容相同。

尽管如此,您将对标记结构做出很多假设。老实说,我想不出一个用例。如果您确定自己有一个,请继续尝试,但也请考虑其他选择。

window.addEventListener("mouseup", function() {
  var sel = window.getSelection ? 
    window.getSelection() :   
    document.selection.createRange();
    
  var display = document.getElementById('selected-output');  
  var output = sel;  
  // If the starting node of the selection is the
  // same as the ending node of the selection 
  // (i.e. the selection doesn't cross nodes)
  if (sel.anchorNode && (sel.anchorNode == sel.extentNode)) {
    if (sel.toString() == sel.anchorNode.textContent) {
      output = sel.anchorNode.parentElement.outerHTML;
    }
  }
  
  display.innerText = output;

});
body {
  background-color: #ffffff;
  font-family: sans-serif;
  padding: 1em;
}
.select-this {
  background-color: #f2f2f2;
  padding: 1em;
  margin: 1em 0;
}
.explanation {
}

.selected {
  background-color: #dddddd;
  border-radius: 3px;
  border: 1px solid #aaaaaa;
  padding: 1em;
}
<div class="select-this">
  <div>Here is some text. You can <em>select</em> it if you want.</div>

  A div just closed.

  <h1>This is an H1 tag.</h1>
  <p>This is a P tag.</p>
  <p>I'm just giving us some stuff to select. 
  <strong>Lorem ipsum,</strong> et cetera.</p>
</div>

<p class="explanation">
If you select something above, it should show up here:</p>

<div class="selected">
  <div id="selected-output">
  </div>
</div>