2011-03-05 16 views
6

tiene ninguna manera por ExecCommand se unen con un elemento div no para todo el documento, de que este intento:conjunto ExecCommand sólo para un div

document.getElementById('div').execcommand(...) 

pero tiene un error:

execcommand is not a function 

se tiene alguna forma de vincular el comando exec con solo elemento div no todo el documento !! no me gusta usar el método iframe.

+0

¿Cuándo desea que se active el comando? Cuando se hace clic en el div –

+0

@Pekka, ¿me puede explicar más – mkotwd

+0

? Enlazar un comando a un elemento no tiene sentido. ¿Qué quieres que suceda exactamente? –

Respuesta

15

Esto es más fácil de hacer en el IE que otros navegadores porque TextRange objetos de IE tienen un método execCommand(), lo que significa que un comando se puede ejecutar en una sección del documento sin necesidad de cambiar la selección y habilitar temporalmente designMode (que es lo que debe hacer en otros navegadores). He aquí una función para hacer lo que quiere limpiamente:

function execCommandOnElement(el, commandName, value) { 
    if (typeof value == "undefined") { 
     value = null; 
    } 

    if (typeof window.getSelection != "undefined") { 
     // Non-IE case 
     var sel = window.getSelection(); 

     // Save the current selection 
     var savedRanges = []; 
     for (var i = 0, len = sel.rangeCount; i < len; ++i) { 
      savedRanges[i] = sel.getRangeAt(i).cloneRange(); 
     } 

     // Temporarily enable designMode so that 
     // document.execCommand() will work 
     document.designMode = "on"; 

     // Select the element's content 
     sel = window.getSelection(); 
     var range = document.createRange(); 
     range.selectNodeContents(el); 
     sel.removeAllRanges(); 
     sel.addRange(range); 

     // Execute the command 
     document.execCommand(commandName, false, value); 

     // Disable designMode 
     document.designMode = "off"; 

     // Restore the previous selection 
     sel = window.getSelection(); 
     sel.removeAllRanges(); 
     for (var i = 0, len = savedRanges.length; i < len; ++i) { 
      sel.addRange(savedRanges[i]); 
     } 
    } else if (typeof document.body.createTextRange != "undefined") { 
     // IE case 
     var textRange = document.body.createTextRange(); 
     textRange.moveToElementText(el); 
     textRange.execCommand(commandName, false, value); 
    } 
} 

Ejemplos:

var testDiv = document.getElementById("test"); 
execCommandOnElement(testDiv, "Bold"); 
execCommandOnElement(testDiv, "ForeColor", "red"); 
+0

guau, muchas gracias, funcionan exactamente como quiero :) – mkotwd

+0

increíble ... muchas gracias! – enloz

+0

¿Podemos escribir algunos datos en el div – Nayeem

3

Tal vez esto le ayuda a cabo:

Example code 1 en esta página tiene la ExecCommand en un div mediante el uso de una función. ¿No estás seguro de si eso es lo que buscas? ¡Buena suerte!

Editar: me di cuenta de cómo poner el código aquí: o

<head> 
<script type="text/javascript"> 
    function SetToBold() { 
     document.execCommand ('bold', false, null); 
    } 
</script> 
</head> 
<body> 
     <div contenteditable="true" onmouseup="SetToBold();"> 
     Select a part of this text!  
     </div> 
</body> 
2

javascript:

var editableFocus = null; 

    window.onload = function() { 
    var editableElements = document.querySelectorAll("[contenteditable=true]"); 

    for (var i = 0; i<editableElements.length; i++) { 
     editableElements[i].onfocus = function() { 
     editableFocus = this.id; 
     } 
    }; 
    } 

    function setPreviewFocus(obj){ 
    editableFocus = obj.id 
    } 

    function formatDoc(sCmd, sValue) { 
    if(editableFocus == "textBox"){ 
     document.execCommand(sCmd, false, sValue); 
    } 
    } 

HTML:

<div id="textBox" contenteditable="true"> 
Texto fora do box 
</div> 

<div contenteditable="true"> 
Texto fora do box 
</div> 

<button title="Bold" onclick="formatDoc('bold');">Bold</button> 
+0

Esto es genial. ¡Gracias! – yanike

0

Puede que sea sencillo, y agrega esto a tu div.

<div contenteditable="true" onmouseup="document.execCommand('bold',false,null);"> 
Cuestiones relacionadas