使用getSelection在链接中包装链接

using getSelection to wrap a link within a link

本文关键字:链接 包装 getSelection 使用      更新时间:2023-09-26

我已经盯着这个问题一段时间了,现在还没有设法得到一个有效的解决方案。

我正在使用Rangy库来确保对range的最佳支持。

  1. 创建一个选区并使用链接换行。
  2. 为已经链接的选区创建一个完整的选区,并用一个链接替换它。

我希望转换以下内容,其中|是一个选择范围。

<>之前链接到|添加链接到之前
<a href="http://example.com">link to |add a link| to</a>
预期

<>之前链接到|添加链接到之前
<a href="http://example.com">link to</a> |<a href="http://example.com/pre">add a link</a>| <a href="http://example.com">to</a>

Test Expectations Plnkr

谢谢你的帮助。

更新(2013-05-15 21:37 UTC):

我有以下

range = document.getSelection();
link = document.createElement('a');
link.href = "http://example.com/new";
range.surroundContents(link);

我也更新了plnkr测试

我已经找到了一个解决方案,可以支持所有3种情况。

rangy.createModule('SafeWrapLink', function(api, module) {
  var surroundSelectionWithLink;
  surroundSelectionWithLink = (function(href) {
    var after, afterLink, afterLinkHref, before, beforeLink, beforeLinkHref, currentLink, fullText, link, par, parNode, range, selectionText;
    range = document.getSelection().getRangeAt(0);
    selectionText = range.toString();
    if (range.commonAncestorContainer.nodeName !== "#text") {
      beforeLinkHref = range.commonAncestorContainer.childNodes[0].getAttribute('href');
      afterLinkHref = range.commonAncestorContainer.childNodes[2].getAttribute('href');
      par = range.commonAncestorContainer;
      parNode = par;
    } else {
      par = range.commonAncestorContainer.parentNode;
      currentLink = par.getAttribute('href');
      parNode = par.parentNode;
    }
    fullText = par.innerText;
    before = fullText.match(new RegExp("^(.*)" + selectionText))[1];
    after = fullText.match(new RegExp(selectionText + "(.*)$"))[1];
    // Build link for before selection
    beforeLink = document.createElement('a');
    beforeLink.href = beforeLinkHref || currentLink;
    beforeLink.innerText = before;
    // Build link to insert
    link = document.createElement('a');
    link.href = href;
    link.innerText = selectionText;
    // Build link for after selection
    afterLink = document.createElement('a');
    afterLink.href = afterLinkHref || currentLink;
    afterLink.innerText = after;
    // Append the links in order
    if (beforeLink.innerText.length > 0) {
      parNode.appendChild(beforeLink);
    }
    parNode.appendChild(link);
    if (afterLink.innerText.length > 0) {
      parNode.appendChild(afterLink);
    }
    // remove old linking
    if (par === range.commonAncestorContainer) {
      par.removeChild(par.childNodes[0]);
      return par.removeChild(par.childNodes[1]);
    } else {
      return parNode.removeChild(par);
    }
  });
  return api.util.extend(api, {
    surroundSelectionWithLink: surroundSelectionWithLink
  });
});

,然后在进行选择后调用以下

rangy.surroundSelectionWithLink('http://www.example.com/added');

查看plnkr.co上的测试和活动代码