Pregunta

Estoy tratando de identificar si un texto seleccionado (en Firefox) está en negrita o no? Para por ejemplo:.

<p>Some <b>text is typed</b> here</p>

<p>Some <span style="font-weight: bold">more text is typed</span> here</p>

El usuario puede o bien seleccionar una parte del texto en negrita, o el texto en negrita completa. Esto es lo que estoy tratando de hacer:

function isSelectedBold(){
    var r = window.getSelection().getRangeAt(0);
    // then what?
}

Podría usted por favor me ayude?

Gracias
Srikanth

¿Fue útil?

Solución

Si la selección se encuentra dentro de un elemento o documento editable, esto es simple:

function selectionIsBold() {
    var isBold = false;
    if (document.queryCommandState) {
        isBold = document.queryCommandState("bold");
    }
    return isBold;
}

De lo contrario, es un poco más complicado: en los navegadores no-IE, usted tiene que hacer editable temporalmente el documento:

function selectionIsBold() {
    var range, isBold = false;
    if (window.getSelection) {
        var sel = window.getSelection();
        if (sel && sel.getRangeAt && sel.rangeCount) {
            range = sel.getRangeAt(0);
            document.designMode = "on";
            sel.removeAllRanges();
            sel.addRange(range);
        }
    }
    if (document.queryCommandState) {
        isBold = document.queryCommandState("bold");
    }
    if (document.designMode == "on") {
        document.designMode = "off";
    }
    return isBold;
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top