如何使用范围选择将孩子附加到克隆中?

时间:2017-04-24 18:19:07

标签: javascript jquery html

我需要存储2个版本的' start' div,所以我正在制作一个克隆并试图追加“跨越'到一个祖先进入克隆,但它'崩溃。我怎样才能实现目标?



function Func() {
  var sel = window.getSelection();
  if (sel.toString().length != 0 && sel.getRangeAt) {
    se = $('<span style="background-color: #3366CC;" id="NewLink">')[0];
    var rng = sel.getRangeAt(sel.rangeCount - 1);
    var anc = rng.commonAncestorContainer;
    alert("the ancestor of selection is " + anc.textContent);
    rng.surroundContents(se);

    var temp = document.getElementById("start");
    var cl = temp.cloneNode(true);

    var span = document.createElement('span');
    span.innerHTML = sel.toString();
    alert("trying to append child with your selection text to an ancestor into the clone");
    try {
      cl.querySelector(anc).appendChild(span);
      alert(cl.outerHTML);
    } catch (l) {
      alert('Oops it seems something goes wrong');
    }
  }
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
try to select the text below
<div id="start" onmouseup="Func ()">
  <div id="second">
    <a href="#">Link</a>
    <p>
      best things are free...
    </p>
    <p>
      long text ....
    </p>
  </div>
</div>
&#13;
&#13;
&#13;

0 个答案:

没有答案