简体   繁体   中英

execCommand not working properly in ie

The problem is with the execCommand, it is not being executed in IE even in IE10 properly . For instance, When I click bold and keeps on typing, in IE it is not making the letters bold, I have to select the text and click bold in order to make it bold. In all other browsers its will make the letters bold when I click bold button and keeps on typing.

Here is the link to jsfiddle http://jsfiddle.net/Q65Qt/

Here is the code

var oDoc, sDefTxt;

function initDoc() {
    oDoc = document.getElementById("textBox");
    sDefTxt = oDoc.innerHTML;
    if (document.compForm.switchMode.checked) {
        setDocMode(true);
    }
}

function formatDoc(sCmd, sValue) {
    if (validateMode()) {
        document.execCommand(sCmd, false, null);
        oDoc.focus();
    }
}

function validateMode() {
    if (!document.compForm.switchMode.checked) {
        return true;
    }
    alert("Uncheck \"Show HTML\".");
    return false;
}

function setDocMode(bToSource) {
    var oContent;
    if (bToSource) {
        oContent = document.createTextNode(oDoc.innerHTML);
        oDoc.innerHTML = "";
        var oPre = document.createElement("pre");
        oDoc.contentEditable = false;
        oPre.id = "sourceText";
        oPre.contentEditable = true;
        oPre.appendChild(oContent);
        oDoc.appendChild(oPre);
    } else {
        if (document.all) {
            oDoc.innerHTML = oDoc.innerText;
        } else {
            oContent = document.createRange();
            oContent.selectNodeContents(oDoc.firstChild);
            oDoc.innerHTML = oContent.toString();
        }
        oDoc.contentEditable = true;
    }
    oDoc.focus();
}

Here is the link to jsfiddle http://jsfiddle.net/Q65Qt/

Please help, Thanks in advance

The problem isn't with document.execCommand() . Instead, the issue seems to be that the editable element loses focus when a button is clicked and as a result loses the boldness when the focus is restored.

The simplest solution is to prevent the button click stealing the focus. You can do this by using the mousedown event instead of the click event and preventing the browser's default behaviour:

http://jsfiddle.net/Q65Qt/1/

Alternatively, you could make the buttons unselectable. See https://stackoverflow.com/a/12527098/96100 , for example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM