Подтвердить что ты не робот

Как использовать CKEditor в модуле Bootstrap?

Если я использую плагин CKEditor на странице HTML на основе шаблона Bootstrap, он отлично работает, однако, если я вставляю редактор в Bootstrap Modal, например это

<!-- Modal --> 
<div class="modal fade" id="modalAddBrand" tabindex="-1" role="dialog" aria labelledby="modalAddBrandLabel" aria-hidden="true">   
  <div class="modal-dialog modal-lg">
     <div class="modal-content">
       <div class="modal-header">
         <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
         <h4 class="modal-title" id="modalAddBrandLabel">Add brand</h4>
       </div>
       <div class="modal-body">
             <form>
             <textarea name="editor1" id="editor1" rows="10" cols="80">
             This is my textarea to be replaced with CKEditor.
             </textarea>            <script>
             CKEDITOR.replace('editor1');
             </script>
             </form> 
       </div>
       <div class="modal-footer">
         <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
         <button id="AddBrandButton" type="button" class="btn btn-primary">Save</button>
       </div>
     </div>   
   </div> 
</div>

Редактор работает, но все элементы управления формы во всплывающих окнах редактора отключены, если вы попытаетесь добавить ссылку или изображение, например, вы не можете вставить URL-адрес или какое-либо описание, потому что входы отключены.

Любое обходное решение для этой проблемы?

Это пример скрипта: http://jsfiddle.net/7zDay/

4b9b3361

Ответ 1

Это должно помочь http://jsfiddle.net/pvkovalev/4PACy/

$.fn.modal.Constructor.prototype.enforceFocus = function () {
    var $modalElement = this.$element;
    $(document).on('focusin.modal', function (e) {
        var $parent = $(e.target.parentNode);
        if ($modalElement[0] !== e.target && !$modalElement.has(e.target).length
            // add whatever conditions you need here:
            &&
            !$parent.hasClass('cke_dialog_ui_input_select') && !$parent.hasClass('cke_dialog_ui_input_text')) {
            $modalElement.focus()
        }
    })
};

Обновить октябрь 2016 года:

Ссылка CDN для CKEditor была изменена, поэтому я обновил jsfiddle

Ответ 2

Это уже поздно ответить, но трюк css решит проблему.

Значение по умолчанию z-index в модуле Bootstrap 10051 и по умолчанию z-index диалогового окна ckeditor 10010. Хитрость заключается только в том, чтобы увеличить z-индекс диалога ckeditor, как показано ниже. введите ниже код в файл css:

.cke_dialog
{
    z-index: 10055 !important;
}

Ответ 3

См. ответ от aaronsnow в этой теме на форуме ckeditor: http://ckeditor.com/forums/Support/Issue-with-Twitter-Bootstrap

Он дал код. Просто поместите код в файл js и убедитесь, что вы включили файл после jquery и bootstrap

Ответ 4

Я получал Uncaught TypeError: Cannot read property 'fn' of undefined

Поэтому я просто заменил $ внутри script, предоставленный @Pavel Kovalev выше, на jQuery.

jQuery.fn.modal.Constructor.prototype.enforceFocus = function () {
    modal_this = this
    jQuery(document).on('focusin.modal', function (e) {
        if (modal_this.$element[0] !== e.target && !modal_this.$element.has(e.target).length
                && !jQuery(e.target.parentNode).hasClass('cke_dialog_ui_input_select')
                && !jQuery(e.target.parentNode).hasClass('cke_dialog_ui_input_text')) {
            modal_this.$element.focus()
        }
    })
};

Ответ 5

Используйте 100% -ную работу script..

<script type="text/javascript">
    // Include this file AFTER both jQuery and bootstrap are loaded.
    $.fn.modal.Constructor.prototype.enforceFocus = function() {
      modal_this = this
      $(document).on('focusin.modal', function (e) {
        if (modal_this.$element[0] !== e.target && !modal_this.$element.has(e.target).length 
        && !$(e.target.parentNode).hasClass('cke_dialog_ui_input_select') 
        && !$(e.target.parentNode).hasClass('cke_dialog_ui_input_textarea')
        && !$(e.target.parentNode).hasClass('cke_dialog_ui_input_text')) {
          modal_this.$element.focus()
        }
      })
    };
</script>

Спасибо!

Ответ 6

  $(document).on({'show.bs.modal': function () {
                 $(this).removeAttr('tabindex');
      } }, '.modal');

Ответ 7

Не знаю, может быть, в моей версии это уже исправлено, но мое решение:

    $("#messageModal").on('shown.bs.modal', function() {
     CKEDITOR.replace('message', {
       height: '400px',
       width: '100%'
     });
   })

Ответ 8

Все очень просто:

$('#modal').removeAttr('tabindex');

$('#modal').focusout(function(){
    $(this).css({'position':'relative'});
});

$('#modal').focusin(function(){
    $(this).css({'position':'fixed'});
});

Ответ 9

Это очень коротко и просто. импортируйте файлы конфигурации CKEditor Javascript из пути, по которому они хранятся в вашем приложении. Это мое

<script type="text/javascript" src="{% static 'ckeditor/ckeditor-init.js' %}"></script>
<script type="text/javascript" src="{% static 'ckeditor/ckeditor/ckeditor.js' %}"></script>

После этого вы можете вызвать CKEditor, чтобы заменить текстовую область, сделав это

CKEDITOR.replace('topic', {
          uiColor: '#9AB8F3',
			    language: "en-us",
			    toolbar: "Custom",
          height: "200",
          width: "400",
			    skin: "moono",
			    toolbar_Custom: [
			    	["Bold", "Italic", "Underline"], 
			    	["NumberedList", "BulletedList", "-", "Outdent", "Indent", "-", "JustifyLeft", "JustifyCenter", "JustifyRight", "JustifyBlock"], 
			    	["Link", "Unlink"]
			    ],  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script src="http://cdn.ckeditor.com/4.3.4/standard/ckeditor.js"></script>


<!-- Modal --> 
<div class="modal fade" id="modalAddBrand" tabindex="-1" role="dialog">
        <div class="modal-dialog">
        	<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <div class="modal-content">
                <div class="user-box">
                    <h2>Create a new discussion</h2>
                    <form method="post" id="discussion_add" action="#">
	                    <!--FORM FIELD START-->
	                    <div class="form">
	                        <div class="input-container">
	                            <input type="text" id="id_session" name="session" required="true">
	                        </div>
	                        <div class="input-container">
	                        	<textarea cols="40" id="id_topic" name="topic" rows="10"></textarea>
	                        </div>

	                        <div class="input-container">
	                            <button class="btn-style">Create Discussion</button>
	                        </div>
	                    </div>
	                </form>                
                </div>
            </div>
            <div class="clearfix"></div>
        </div>
    </div>
<button data-toggle="modal" data-target="#modalAddBrand">Launch Modal</button>

Ответ 10

Просто откройте /core/config.js в файлах ckeditor, затем измените переменную baseFloatZIndex"

baseFloatZIndex = 10000

в

baseFloatZIndex = 20000

Это изменит начало "z-index" окна вашего редактора и всплывающие окна popups.

Ответ 11

Я думаю, что нашел какое-то решение для этого.

Как сказал @Pavel Kovalev, это как-то связано с Boostraps 4 JS и сосредоточено на модальном скрипте. У меня была такая же проблема, как и у вас.

Существует опция для модалов, называемая "фокус", которая устанавливает фокус на инициализированные модалы. Отключение этой опции заставляет все Ваши входы в модальностях CKEditors работать должным образом. Не имея фокуса на этом модале, без которого я могу жить :)

Подробности смотрите здесь: https://getbootstrap.com/docs/4.3/components/modal/#options

В моем подходе к этому я наконец получил что-то вроде этого:

<div class="modal fade" data-focus="false" id="newsAdd" role="dialog" aria-labelledby="fieldAdd" aria-hidden="true">
...
</div>

Также, вероятно, это хорошая идея для более обширного тестирования, особенно если у вас есть несколько модальностей начальной загрузки с CKEditor на одной странице.

Что касается всех "исправлений", которые можно найти в Интернете. Взгляните, что они, скорее всего, относятся к начальной загрузке 3, где события на модальном уровне отличаются, поэтому они просто не могут работать. В том числе решение @Pavel Kovalev.