2012-06-20 11 views
6

Cómo dividir un nodo/elemento en una posición (selección).Nodo dividido de Rangy (JS/jQuery)

Ejemplo tengo este marcado:

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

(este tubo representa la posición/selección)

quiero convertirlo a:

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

El mantenimiento de la selección.

¿Alguna idea?

I y utilizando la biblioteca Rangy, y también jQuery, pero puede usar JS sin formato, si corresponde.

Respuesta

10

Puede hacer esto creando un rango que se extienda desde el cursor hasta el punto inmediatamente posterior al párrafo y utilizando su método extractContents().

Demostración en directo: http://jsfiddle.net/timdown/rr9qs/2/

Código:

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