Динамический цвет кузова с использованием CKEditor - PullRequest
4 голосов
/ 30 сентября 2010

У меня есть ситуация на CKEditor, которую я хотел бы разрешить. Я использую палитру цветов jQuery, чтобы добавить цвет фона к тегу DIV. Затем я разрешаю пользователю редактировать содержимое тега Div с помощью CKEditor. Однако я заметил, что не существует простого способа взять цвет фона тега div, а затем сделать его цвет фона CKEditor при загрузке редактора.

Я прочитал bodyClass и bodyId и не думаю, что они решают мою проблему. У меня нет элемента класса, но есть объявление встроенного стиля, например

<div class="tp-header" style="background-color:#CCCCCC;">content</div>

Я вызываю CKEditor следующим образом:

var editorId = 'editor1';
var instance = CKEDITOR.instances[editorId];
var color = $('.' + headerElementClass).css('background-color');
if (instance) { CKEDITOR.remove(instance); }
$('#' + editorId).ckeditor({ toolbar: 'BasicHtml', height: '100px', width: '500px', fullPage: false, bodyClass : 'background-color:' + color });
$('#' + editorId).val($('.' + headerElementClass).html());

Обратите внимание на неудачное использование bodyClass . Есть какой-либо способ сделать это? Я бродил по сайту за ответами, но не смог его найти. Я надеюсь, что у кого-то здесь есть ответ.

Ответы [ 2 ]

1 голос
/ 13 июля 2013

codewaggle ответ хороший, но если вы хотите установить встроенные стили для элемента <body> редактора, вы можете сделать это тоже, используя:

editor.document.getBody().setStyle()

или

editor.document.getBody().setStyles()

Однако вам придется повторять это каждый раз после вызова editor.setData () и после того, как пользователь переключится обратно в режим wysiwyg (из исходного режима), потому что эти вещи воссоздают редактор iframe. Чтобы сделать все это, установите ваши стили, используя функцию, скажем setEditorStyle, , в которой вы сначала проверяете, что editor.mode==='wysiwyg' (в противном случае editor.document равно нулю), затем добавьте эту функцию в качестве прослушивателя события instanceReady и mode; и, возможно, также событие contentDom, если вы когда-либо вызывали setData () и впоследствии не хотели вызывать его вручную.

См. Некоторые другие ответы StackOverflow здесь и здесь

1 голос
/ 01 сентября 2011

Я думал об этом и нашел гораздо более простое решение.Я не использую адаптер JQuery CKEditor, поэтому вам может потребоваться изменить его в соответствии с вашей ситуацией.

Я протестировал его, используя стандартный подход интеграции JavaScript.

Краткий обзор: Установите переменные.Создайте экземпляр редактора.

Вставьте этот вызов функции "addCss":

CKEDITOR.instances[editorId].addCss( 'body { background-color: '+color+'; }' );

Это все, что нужно сделать.Вот пример на основе вашего кода:

// I added the "id" attribute:
<div id="editor1" class="tp-header" style="background-color:#CCCCCC;">content</div>

// Declare the variables, I added "headerElementClass".
var headerElementClass = "tp-header";
var color = $('.' + headerElementClass).css('background-color');
var editorId = 'editor1';

// Create the instance.
var instanceOne = CKEDITOR.replace( editorId,
{
  toolbar: 'Basic',
  height: '100px',
  width: '500px',
  fullPage: false,
  customConfig : 'yourCustomConfigFileIfUsed.js'
 });

// Insert the "addCss" function call:
instanceOne.addCss( 'body { background-color: '+color+'; }' );

Вызов функции addCss можно переместить в ваш файл конфигурации, если вы предпочитаете (поместите его вне функции editorConfig).

Будьте здоровы, Джо


Если оставить более сложный подход, кто-тонайдите полезные концепции.

Вы можете использовать (bodyClass: 'nameOfClass'), а затем присвоить значение свойству background-color этого класса.Но это сложно, потому что у вас есть динамический цвет фона.

Чтобы назначить цвет фона динамически, вы можете сделать что-то вроде этого: Начиная с вашего кода и продолжая использовать jQuery:

var editorId = 'editor1';
var instance = CKEDITOR.instances[editorId];
var color = $('.' + headerElementClass).css('background-color');

// Create a unique body id for this instance "editor1" ( bodyIdForeditor1 )
var idForBody = 'bodyIdFor' + editorId;

if (instance) { CKEDITOR.remove(instance); }

// Use bodyId instead of the original bodyClass assignment
$('#' + editorId).ckeditor({ 
  toolbar: 'BasicHtml', 
  height: '100px', 
  width: '500px', 
  fullPage: false, 
  bodyId : idForBody 
});

$('#' + editorId).val($('.' + headerElementClass).html());

// After both the document and editor instance are ready, 
// assign the background color to the body

// Wait for the document ready event
$(document).ready(function(){

  // Wait for the instanceReady event to fire for this (editor1) instance
  CKEDITOR.instances.editor1.on( 'instanceReady', 
    function( instanceReadyEventObj )
    {
      var currentEditorInstance = instanceReadyEventObj.editor;
      var iframeDoc=null;

      // Create a function because these steps will be repeated
      function setIframeBackground()
      {
        // The CKEditor content iframe doesn't have a Name, Id or Class
        // So, we'll assign an ID to the iframe 
        // it's inside a table data cell that does have an Id.
        // The Id of the data cell is "cke_contents_editor1" 
        // Note that the instance name is the last part of the Id
        // I'll follow this convention and use an Id of "cke_contents_iframe_editor1" 

        $("#cke_contents_editor1 iframe").attr("id", "cke_contents_iframe_editor1");

        // Now use the iframe Id to get the iframe document object
        // We'll need this to set the context and access items inside the iframe

        $('#cke_iframe_editor1').each( 
          function(){ iframeDoc=this.contentWindow.document;}
        );

        // Finally we can access the iframe body and set the background color.
        // We set the Id of the body when we created the instance (bodyId : idForBody).
        // We use the iframe document object (iframeDoc) to set the context.
        // We use the "color" variable created earlier

        $('#' + idForBody, iframeDoc).css("background-color", color);
      }

      // Call the function to set the color when the editor instance first loads
      setIframeBackground();

      // When the user switches to "source" view mode, the iframe is destroyed
      // So we need to set the color again when they switch back to "wysiwyg" mode

      // Watch for the "mode" event and check if we're in "wysiwyg" mode
      currentEditorInstance.on( 'mode', function()
      {
        if(currentEditorInstance.mode == 'wysiwyg')
          setIframeBackground();
      });
    }
  );
});

Будь здоров, Джо

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...