document.execCommand() FontSize in pixels?

后端 未结 8 1895
一向
一向 2020-11-29 06:55

How can I change font size to 30px (for example) using document.execCommand?

This:

document.execCommand(\"fontSize\", false, \"30px\");
         


        
相关标签:
8条回答
  • 2020-11-29 07:31

    Function

    var execFontSize = function (size, unit) {
        var spanString = $('<span/>', {
            'text': document.getSelection()
        }).css('font-size', size + unit).prop('outerHTML');
    
        document.execCommand('insertHTML', false, spanString);
    };
    

    Execute

    execFontSize(30, 'px');
    
    0 讨论(0)
  • 2020-11-29 07:32

    Found a solution in pure JavaScript that works for multiple lines with custom HTML (colors, font families).

    Get the selection of the document. Parse the selection and save the html tags from it. Then with document.execCommand insert the selected html inside a div that has inline style. Also a benefit when using document.execCommand('insertHTML', false, html) is that you get undo in WYSIWYG editor.

    This is the function:

    function fontSize(size) {
    
        var sel = document.getSelection(); // Gets selection
    
        var selectedHtml = "";
        if (sel.rangeCount) {
            var container = document.createElement("div");
            for (var i = 0, len = sel.rangeCount; i < len; ++i) {
                container.appendChild(sel.getRangeAt(i).cloneContents());
            }
            const children = container.getElementsByTagName("*")
            for(let child of children) {
                if(child.style.fontSize) {
                    child.style.fontSize = `${size}px`
                }
            }
            selectedHtml = container.innerHTML;
        }
    
        let html = `<div style="font-size: ${size}px;">${selectedHtml}</div>`
        document.execCommand('insertHTML', false, html);
    }
    

    Hope it helps.

    0 讨论(0)
提交回复
热议问题