Pregunta

Digamos que resalto algo de texto en la página usando mi mouse. ¿Cómo puedo eliminar todo el texto resaltado usando JavaScript?

Gracias.

¿Fue útil?

Solución

He entendido la pregunta un poco diferente. Creo que desea saber cómo eliminar el texto seleccionado del documento, en cuyo caso podría usar:

function deleteSelection() {
    if (window.getSelection) {
        // Mozilla
        var selection = window.getSelection();
        if (selection.rangeCount > 0) {
            window.getSelection().deleteFromDocument();
            window.getSelection().removeAllRanges();
        }
    } else if (document.selection) {
        // Internet Explorer
        var ranges = document.selection.createRangeCollection();
        for (var i = 0; i < ranges.length; i++) {
            ranges[i].text = "";
        }
    }
}

Si solo desea borrar el resaltado en sí mismo y no eliminar el texto que se resalta, lo siguiente debería ser el truco:

function clearSelection() {
    if (window.getSelection) {
        window.getSelection().removeAllRanges();
    } else if (document.selection) {
        document.selection.empty();
    }
}

Otros consejos

IE 4 y el antiguo Netscape solían tener un método para hacer esto ... Ya no es adecuado (ni compatible).

Su mejor opción sería utilizar Javascript para enfocar () en un objeto y luego desenfocar () también, efectivamente, como hacer clic fuera del objeto.

document.getElementById("someObject").focus();
document.getElementById("someObject").blur();
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top