开发者

Changing content CSS on the run in TinyMCE or CKEditor

I have a form in which I want to edit a HTML template. It has 2 textareas, one for the HTML and another one for the CSS.

I'd like to use either TinyMCE or CKEditor for the HTML textarea.

Is there any way to change the content CSS in eith开发者_StackOverflower of them to match the CSS in the CSS textarea on the run, so when I change the CSS it is automatically loaded into the editor?

Thanks.


I have no experience with CKEditor, but i know that it is possible with TinyMce. What you need to do is to write an own plugin which will provide the necessary functionality.

OnNodeChange in the 2nd textarea (the one with your css) you need to update the head of the first editors iframe. This code snippet to be executed on a special action (for example onNodeChange) should point you into the right direction:

var DEBUG = false;
var css_code = tinymce.editors[1].getContent(); // get content of 2nd editorinstance on page (your css)


iframe_id = tinymce.editors[0].id+'_ifr';

with(document.getElementById(iframe_id).contentWindow){
    var h=document.getElementsByTagName("head");
    if (!h.length) {
        if (DEBUG) console.log('length of h is null');
        return;
    }
    var newStyleSheet=document.createElement("style");
    newStyleSheet.type="text/css";
    h[0].appendChild(newStyleSheet);
    try{
        if (typeof newStyleSheet.styleSheet !== "undefined") {
        newStyleSheet.styleSheet.cssText = css_code;
    }
    else {
        newStyleSheet.appendChild(document.createTextNode(css_code));
        newStyleSheet.innerHTML=css_code;
    }
}

Be aware that this code will add a new style sheet everytime it is called - yielding in increasing the editor iframes head. So i think best practice is to clean up the last inserted style before appliing the new one. Removing the last Node of the head shozld be sufficient.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜