【问题标题】:How to expand selection to include surrounding link tag?如何扩展选择以包括周围的链接标签?
【发布时间】:2013-12-15 17:46:23
【问题描述】:

我有一个包含 html 的可编辑 div:

"hello "<a href='#'>this is the title</a>" goodbye"

如果我只选择链接 html 的“他是”部分,然后运行:

document.execCommand('unlink');

标签被分成两个标签离开:

<a href='#'>t</a>"his is"<a href='#'>the title</a>

有没有办法修改选择扩展为整个链接标签来移除整个链接?

selection = document.getSelection() ?

更新

感谢盖比!我采用了他的解决方案并对其进行了一些修改,以扩展过去互换的粗体和斜体标签:

var selection = document.getSelection(); // get selection
var node = selection.anchorNode; // get containing node


var baseChild = function(parent, last) {
  var children = parent.childNodes.length;
  if (children == 0) {
    return parent;
  }
  var child = (last == true) ? children-1 : 0;

  return baseChild( parent.childNodes(child));
}

var findAndRemove = function(node) {

  while (node && node.nodeName !== 'A'){ // find closest link - might be self
    node = node.parentNode;
  }

  if (node){ // if link found
    var range = document.createRange(); //create a new range
    range.selectNodeContents(node); // set range to content of link
    selection.addRange(range); // change the selection to the link
    document.execCommand('unlink'); // unlink it
    if ( node.previousSibling ){
      findAndRemove(baseChild(node.previousSibling, true));
    }
    if ( node.nextSibling ){
      findAndRemove(baseChild(node.nextSibling, false ));
    }
  }
}
findAndRemove(node);

【问题讨论】:

    标签: javascript selection contenteditable execcommand


    【解决方案1】:

    试试

      var selection = document.getSelection(), // get selection
          node = selection.anchorNode; // get containing node
    
      while (node && node.nodeName !== 'A'){ // find closest link - might be self
        node = node.parentNode;
      }
    
      if (node){ // if link found 
        var range = document.createRange(); //create a new range 
        range.selectNodeContents(node); // set range to content of link
        selection.addRange(range); // change the selection to the link
        document.execCommand('unlink'); // unlink it
      }
    

    演示地址 http://codepen.io/gpetrioli/pen/lkrFi

    【讨论】:

    • window.getSelection()document.getSelection() 更兼容,因此应该首选,尽管它们现在被指定为别名,因此在当前浏览器中很好。
    【解决方案2】:

    试试这个,

    var a = document.getElementsByTagName('a');
    
    while(a.length) {
        var parent = a[ 0 ].parentNode;
        while( a[ 0 ].firstChild ) {
            parent.insertBefore(  a[ 0 ].firstChild, a[ 0 ] );
        }
         parent.removeChild( a[ 0 ] );
    }
    

    【讨论】:

    • 不管选择什么,都会清除我所有的 a 标签
    猜你喜欢
    • 1970-01-01
    • 2020-06-28
    • 2012-04-24
    • 2016-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-26
    • 2015-04-29
    相关资源
    最近更新 更多