2012-06-20 10 views
6

Wie würde ich einen Knoten/Element an einer Position (Auswahl) teilen.Rangy (JS/jQuery) Split-Knoten

Beispiel I haben diese Auszeichnungs:

<p>This is <a href="">a te|st</a>, you like?</p> 

(Dieses Rohr stellt die Position/Auswahl)

ich es zu konvertierende:

<p>This is <a href="">a te</a></p>|<p><a href="">st</a>, you like?</p> 

Aufrechterhaltung der Selektion.

Irgendwelche Ideen?

Ich und die Rangy-Bibliothek und auch jQuery, kann aber verwenden, roh JS, falls zutreffend.

Antwort

10

Sie können dies tun, indem Sie einen Bereich erstellen, der sich von der Einfügemarke bis zu dem Punkt unmittelbar nach dem Absatz erstreckt und seine Methode extractContents() verwendet.

Live-Demo: http://jsfiddle.net/timdown/rr9qs/2/

Code:

var sel = rangy.getSelection(); 
if (sel.rangeCount > 0) { 
    // Create a copy of the selection range to work with 
    var range = sel.getRangeAt(0).cloneRange(); 

    // Get the containing paragraph 
    var p = range.commonAncestorContainer; 
    while (p && (p.nodeType != 1 || p.tagName != "P")) { 
     p = p.parentNode; 
    } 

    if (p) { 
     // Place the end of the range after the paragraph 
     range.setEndAfter(p); 

     // Extract the contents of the paragraph after the caret into a fragment 
     var contentAfterRangeStart = range.extractContents(); 

     // Collapse the range immediately after the paragraph 
     range.collapseAfter(p); 

     // Insert the content 
     range.insertNode(contentAfterRangeStart); 

     // Move the caret to the insertion point 
     range.collapseAfter(p); 
     sel.setSingleRange(range); 
    } 
}