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");
¿Cuándo desea que se active el comando? Cuando se hace clic en el div –
@Pekka, ¿me puede explicar más – mkotwd
? Enlazar un comando a un elemento no tiene sentido. ¿Qué quieres que suceda exactamente? –