简体   繁体   English

execCommand在IE中无法正常工作

[英]execCommand not working properly in ie

The problem is with the execCommand, it is not being executed in IE even in IE10 properly . 问题出在execCommand上,即使在IE10中也没有在IE中执行。 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. 例如,当我单击粗体并继续输入时,在IE中,它不是使字母变为粗体,我必须选择文本并单击粗体以使其变为粗体。 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/ 这是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/ 这是jsfiddle的链接http://jsfiddle.net/Q65Qt/

Please help, Thanks in advance 请帮助,在此先谢谢

The problem isn't with document.execCommand() . 问题不在于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: 您可以通过使用mousedown事件而不是click事件并阻止浏览器的默认行为来做到这一点:

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

Alternatively, you could make the buttons unselectable. 或者,您可以使按钮不可选。 See https://stackoverflow.com/a/12527098/96100 , for example. 例如,请参阅https://stackoverflow.com/a/12527098/96100

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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