2
votes

I'm using TinyMCE 4. Unfortunately the "backcolor" control seems to only allow changes to text, not a whole paragraph. Even when I select a paragraph in the status bar of TinyMCE and apply a background color, it's only applied to the inner span, not the paragraph itself. I would need to set the background color for the complete content, not only parts of it. This should be applied to the HTML output, something like

<div style="background-color: #f00">[complete editor content]</div>

Thanks for any help.

3

3 Answers

1
votes

You can use this code to access the tinymce's body to set background color:

tinymce.activeEditor.getBody().style.backgroundColor = '#<yourcolor>';

Disadvantage: Setting the background color that way will not change/affect the html content inside the editor. So you have to treat/update/store that value in a separate way.

You can also add a button on initialising tinymce:

tinymce.init({
...
        setup: function (editor) {
            editor.addButton('mybutton', {
                text: 'Set bgColor',
                icon: false,
                onclick: function () {
                    editor.getBody().style.backgroundColor = '#E5FFCC';
                }
            });
...
});
0
votes

You have to reach the editable content body in the dynamically generated iframe. The iframe is generated after the initialization of the editor.

If your textarea id is foo, the id of the iframe is foo_ifr.

You may also open the editor with firebug or developer tools and use dom explorer, you may see the inner dynamically generated components.

use:

var iframe = document.getElementsByTagName("iframe")[0];
// or
var iframe = document.getElementsById("foo_ifr");

// check if iframe.contentDocument is cross-browser, i tested with IE 11.
var innerBody = iframe.contentDocument.getElementsByClassName("mceContentBody")[0];
innerBody.style.backgroundColor="red";
0
votes

To get the custom styling that you want, you have to create new custom style formats when the editor is being initialized. This gives you the ability to define css styling to the element. For example

HTML

<form>
    <textarea></textarea>
</form>

JS

tinymce.init({
    selector: 'textarea',
    //merge with default formats
    style_formats_merge: true,
    //set up custom style formats 
    style_formats: [
        {title: 'Red Background', block: 'p', styles: {
            'background-color': '#ff0000', 
            'color':'white',
            'padding': '7px'}
        },
        {title: 'Blue Background', block: 'p', styles: {
            'background-color': '#0000ff', 
            'color':'white',
            'padding': '7px'}
        }
    ]
});

This merges two new custom formats with the default formats. See this DEMO