2011-03-22 27 views
13

¿Existe una función js simple que pueda usar para reemplazar la selección del documento actual con algún html mío?javascript reemplazar selección todos los navegadores

Por ejemplo, diga que el documento contiene un <p>AHAHAHA</p> en algún lugar y el usuario selecciona el primer trozo de texto "ha".

Ahora quiero reemplazar esto con algo como: <span><font color="red">hoho</font></span>

Cuando Google por * Javascript sustituir a la selección * No puedo obtener una respuesta simple y sencillo!

Respuesta

24

Sí. A continuación se hará en todos los principales navegadores, con una opción para seleccionar el contenido insertado posteriormente conforme a lo solicitado en los comentarios (aunque esta parte no está implementado para IE < = 8):

Demostración en directo: http://jsfiddle.net/bXsWQ/147/

código:

function replaceSelection(html, selectInserted) { 
    var sel, range, fragment; 

    if (typeof window.getSelection != "undefined") { 
     // IE 9 and other non-IE browsers 
     sel = window.getSelection(); 

     // Test that the Selection object contains at least one Range 
     if (sel.getRangeAt && sel.rangeCount) { 
      // Get the first Range (only Firefox supports more than one) 
      range = window.getSelection().getRangeAt(0); 
      range.deleteContents(); 

      // Create a DocumentFragment to insert and populate it with HTML 
      // Need to test for the existence of range.createContextualFragment 
      // because it's non-standard and IE 9 does not support it 
      if (range.createContextualFragment) { 
       fragment = range.createContextualFragment(html); 
      } else { 
       // In IE 9 we need to use innerHTML of a temporary element 
       var div = document.createElement("div"), child; 
       div.innerHTML = html; 
       fragment = document.createDocumentFragment(); 
       while ((child = div.firstChild)) { 
        fragment.appendChild(child); 
       } 
      } 
      var firstInsertedNode = fragment.firstChild; 
      var lastInsertedNode = fragment.lastChild; 
      range.insertNode(fragment); 
      if (selectInserted) { 
       if (firstInsertedNode) { 
        range.setStartBefore(firstInsertedNode); 
        range.setEndAfter(lastInsertedNode); 
       } 
       sel.removeAllRanges(); 
       sel.addRange(range); 
      } 
     } 
    } else if (document.selection && document.selection.type != "Control") { 
     // IE 8 and below 
     range = document.selection.createRange(); 
     range.pasteHTML(html); 
    } 
} 

Ejemplo:

replaceSelection('<span><font color="red">hoho</font></span>', true); 
+0

fresco! ¿Podría agregar una pequeña cantidad de comentarios, como las condiciones para IE y para otros navegadores, gracias! –

+2

@Marco: Hecho ... –

+1

no funcionó en Safari 5.1 para Mac –

6

puede utilizar la biblioteca Rangy http://code.google.com/p/rangy/

A continuación, puede hacer

var sel = rangy.getSelection(); 
var range = sel.getRangeAt(0); 

range.deleteContents(); 
var node = range.createContextualFragment('<span><font color="red">hoho</font></span>'); 
range.insertNode(node); 
Cuestiones relacionadas