如何检测选择中的链接?

时间:2017-04-22 19:17:51

标签: javascript dom

如果用户选择“a”标签中的文字,我必须将其删除。如果一个大于div的链接在新行上占用,当我开始选择中间时,我只得到文本。那么我如何才能达到这个目的并有效地获得链接?

  function GetSelectedText () {
  
   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;
        }
    }
    alert(html);
  }
.textField 
{
width: 50%;
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body onmouseup="GetSelectedText ()">
<div class="textField">Carnotaurus, a large theropod dinosaur, lived during the Late Cretaceous period. Known from a single well-preserved skeleton found in Argentina, it is a member of the Abelisauridae family<a href="#">and one of the best-understood theropods from the Southern Hemisphere. Carnotaurus (derived from Latin for "meat-eating bull") had thick horns above the eyes, and a very deep skull on a muscular neck.</a>t was a lightly built, bipedal predator, 8 to 9 m (26.2 to 29.5 ft) long, weighing at least 1.35 metric tons (1.49 short tons). It had small, vestigial forelimbs and long and slender hindlimbs. Preserved skin impressions show a mosaic of small scales interrupted by large bumps that lined the sides of the animal. </div>
</body>
</html>

0 个答案:

没有答案