2013-12-15 120 views
2

我有一個包含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() ? 

UPDATE

感謝加比!我把他的解決方案,並修改了它有點伸過交換粗體和斜體標籤:

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); 

回答

4

嘗試

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

+1

'window.getSelection()'比'document.getSelection()'更兼容,所以應該首選,儘管它們現在被指定爲別名,所以在當前瀏覽器中很好。 –

+0

@TimDown謝謝你的提醒。 –

-1

試試這個,

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 ]); 
} 
+0

以及將清除所有我的標籤,無論選擇什麼 –

相關問題