Назначение некоторого стиля из поля стилей в CKEditor через JavaScript - PullRequest
1 голос
/ 10 мая 2011

Как я могу имитировать выбор пользователем какого-либо стиля из поля стилей через JS? Я хочу поставить несколько сочетаний клавиш, которые назначают некоторые популярные стили одним щелчком мыши.

РЕДАКТИРОВАТЬ:

  • Мне все равно, будет ли это кнопка в редакторе или внешняя кнопка.
  • Я не хочу CSS-стиль назначение; Я хочу присвоить CKEditor-style (те из блока стилей).

Ответы [ 2 ]

3 голосов
/ 19 мая 2011

Я не использовал CKEditor, но я увидел ваш вопрос и подумал: «Это было бы интересно выяснить».Ну, вот что я понял:

(да, я нашел ужасную документацию, но не в этом дело ... Я, однако, дам им реквизиты для комментирования их кода.)

///
// function to add buttons that trigger styles to be applied.
//
// editor - CKEDITOR - instance of editor you want command attached to.
// buttonName - String - name of the button
// buttonLabel - String - humane readable name of the button
// commandName - String - name of command, the way to call this command from CKEDITOR.execCommand()
// styleDefinition - StyleDefinition - obj defining the style you would like to apply when this command is called.
///

var addButtonCommand = function( editor, buttonName, buttonLabel, commandName, styleDefiniton )
{
    var style = new CKEDITOR.style( styleDefiniton );
    editor.attachStyleStateChange( style, function( state )
        {
            !editor.readOnly && editor.getCommand( commandName ).setState( state );
        });
    editor.addCommand( commandName, new CKEDITOR.styleCommand( style ) );
    editor.ui.addButton( buttonName,
        {
            label : buttonLabel,

            command : commandName
            //adding an icon here should display the button on the toolbar.
            //icon : "path to img",
        });
};

//Get the editor instance you want to use.  Normally the same as the ID of the textarea CKEditor binds to.
var editor1 = CKEDITOR.instances.editor1;

//If you look at ckeditor/_source/plugins/styles/default.js you will see that this selects the first element.  That list is read into the array 'default'.
var blueTitleStyle = CKEDITOR.stylesSet.registered.default[0];

//Or, you can define the style like this: See http://dev.ckeditor.com/wiki/Components/Styles for more info on style definitions.
var blueTitleStyle = { 
    name : 'Blue Title',
    element : 'h3',
    styles : { 'color' : 'Blue' }
};

addButtonCommand(editor1, 'BlueTitle', 'BlueTitle', 'bluetitle', blueTitleStyle);

Вот функция Javascript, чтобы помочь вашим событиям клика:

//function used to execute the command.  Only used for calling the command when not calling from a button. (Like an A with an onClick bound to it.)
    //pulled this function right out of the api.html example in the ckeditor/_samples dir.
    function ExecuteCommand( commandName )
    {
        // Get the editor instance that we want to interact with.
        var oEditor = CKEDITOR.instances.editor1;

        // Check the active editing mode.
        if ( oEditor.mode == 'wysiwyg' )
        {
            // Execute the command.
            // http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.editor.html#execCommand
            oEditor.execCommand( commandName );
        }
        else
        {
            alert( 'You must be in WYSIWYG mode!' );
        }
    }

Теперь вы можете создать ссылку, например так:

<a href='#' class='setBlueTitle'>Set Blue Title</a>

и использовать немного jQueryПриправить это:

 <script type="text/javascript">
            $(document).ready(function(){
                $(".setBlueTitle").onClick(function(e){
                    //stops the click from changing the page and whatever other default action would happen.
                    e.preventDefault();

                    ExecuteCommand('bluetitle');
                });
            });
        </script>

Я не уверен на 100% в части значка кнопки.У меня не было значка, чтобы попробовать его.Но, согласно нескольким постам, все должно работать нормально.В любом случае, привязка jQuery-кликов работает.

Вот и все!Мне пришлось немало покопаться, чтобы понять это, но, безусловно, приятно видеть, как это работает!

0 голосов
/ 12 мая 2011

Вот один из вариантов

Во-первых, вы можете настроить желаемые стили, которые вы хотите опробовать в классе CSS.Затем вы можете установить className для тестового div, когда нажимаете эту кнопку.Вот простой пример:

test.css:

.bold {
   font-weight: bold; 
}

.italic {
   font-style: italic; 
}

test.html

<html>
<head>
    <link rel="stylesheet" type="text/css" href="test.css" />
</head>
<body>
    <input type="button" onclick="document.getElementById('testStyleDiv').className='bold'" value="bold"/>
    <input type="button" onclick="document.getElementById('testStyleDiv').className='italic'" value="italic"/>

    <div id="testStyleDiv">foo</div>
</body>
</html>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...