简体   繁体   中英

problems with execCommand justification in Firefox?

I am building a very simple WYSWIG editor for a div with contenteditable = "true" . I am using execCommand to do simple formatting such as bold, italicize, and underline along with text justification.

PROBLEM: Bold, italic, underline all work but using justifyCenter (or any justify) doesn't work in Firefox but works in Chrome and Safari. Chrome and Safari don't seem to like my justifyRight but works just fine with justifyLeft and justifyCenter. In Firefox I get the following:

uncaught exception: [Exception... "Component returned failure code: 0x80004005 (NS_ERROR_FAILURE) [nsIDOMNSHTMLDocument.execCommand]" nsresult: "0x80004005 (NS_ERROR_FAILURE)"

I can't figure out what is wrong but wonder it if might have something to do with designMode needing to be set to on in Firefox? However, bold, italic, and underline are working just fine without me explicitly turning on designMode.

Any ideas? Thanks in advance.

I know it's sort of a late answer, and you probably figured it out already, but for anyone who hasn't, try setting contenteditable to true for the body. I'm trying to find a way around this because every browser justifies the text just fine without it on, and I don't want the whole page editable.

The bug is referenced here : https://bugzilla.mozilla.org/show_bug.cgi?id=442186 Someone proposed this workaround :

try
{
    document.execCommand('justifyright', false, null);
}
catch (e)
{
    //special case for Mozilla Bug #442186
    if(e && e.result == 2147500037)
    {
        //probably firefox bug 442186 - workaround
        var range = window.getSelection().getRangeAt(0);
        var dummy = document.createElement('br');

        //find node with contentEditable
        var ceNode = range.startContainer.parentNode;
        while(ceNode && ceNode.contentEditable != 'true')
            ceNode = ceNode.parentNode;

        if(!ceNode)
            throw 'Selected node is not editable!';

        ceNode.insertBefore(dummy, ceNode.childNodes[0]);
        document.execCommand('justifyright', false, null);
        dummy.parentNode.removeChild(dummy);
    }
    else if(console && console.log)
        console.log(e);
}

It consists in creating a dummy element (a <br /> ) and remove it after the execution of the justify* command.

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