2012-06-20 25 views
6

Come si suddividerebbe un nodo/elemento in una posizione (selezione).Rangy (JS/jQuery) nodo diviso

Esempio ho questo markup:

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

(questo tubo rappresenta la posizione/selezione)

voglio convertirlo:

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

Mantenendo la selezione.

Qualche idea?

I e utilizzando la libreria Rangy e anche jQuery, ma è possibile utilizzare JS non elaborato, se applicabile.

risposta

10

È possibile eseguire questa operazione creando un intervallo che si estende dal punto di inserimento a punto immediatamente dopo il paragrafo e utilizzando il suo metodo extractContents().

Demo online: http://jsfiddle.net/timdown/rr9qs/2/

Codice:

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