2012-06-20 14 views
6

Jak podzielić węzeł/element na pozycję (wybór).Rangy (JS/jQuery) węzeł podziału

Przykład I mają ten znacznik:

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

(ta rura reprezentuje pozycję/selekcji)

I ma, aby przekształcić go do:

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

Utrzymanie wybór.

Wszelkie pomysły?

I i przy użyciu biblioteki Rangy, a także jQuery, ale w razie potrzeby można użyć surowego JS.

Odpowiedz

10

Można to zrobić, tworząc zakres, który rozciąga się od karetki do punktu bezpośrednio po akapicie i przy użyciu metody extractContents().

żywo demo: http://jsfiddle.net/timdown/rr9qs/2/

Kod:

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