Высота CKEditor 3.0

Есть ли способ установить высоту CKEditor 3.0 в процентах, например 100%, чтобы он занимал все окно?

В настоящее время я использую абсолютные значения, но они плохо сочетаются с моим пользовательским интерфейсом :(

CKEDITOR.replace('editor1',{
    height: '600px'
});

person clops    schedule 09.10.2009    source источник


Ответы (10)


После долгой работы с этим изменением размера на ckeditor 4 я придумал это, которое отлично работает для меня:

в config.js:

// prevent flashing of resizing by setting the content panel to zero height before it is resized
config.height = '0px';
config.width = '100%'; 

jQuery:

$(document).ready(function(){

    // resize the editor(s) while the instance is ready
    CKEDITOR.on('instanceReady', function() { 
        var textEditHeight      = $(".textPanel").height();
        var ckTopHeight         = $("#cke_1_top").height();
        var ckContentsHeight    = $("#cke_1_contents").height();

        for (var i = 1; i < 10; i++) {
            $("#cke_"+i+"_contents").height( (textEditHeight - ckTopHeight - 10) + "px");

        }
    });

    // resize the editor(s) while resizing the browser
    $(window).resize(function(){
        var textEditHeight      = $(".textPanel").height();
        var ckTopHeight         = $("#cke_1_top").height();
        var ckContentsHeight    = $("#cke_1_contents").height();

        for (var i = 1; i < 10; i++) {
            $("#cke_"+i+"_contents").height( (textEditHeight - ckTopHeight - 10) + "px");
        }
    });

});

У меня есть несколько экземпляров редактора одного и того же размера на вкладках для каждого языка, отсюда и цикл for. Если у вас есть один редактор, вы можете оставить эту строку и использовать стандартный идентификатор cke

// prevent flashing of resizing by setting the content panel to zero height before it is resized
config.height = '0px';
config.width = '100%'; 
contents.

В этом примере высоты берутся из первой панели инструментов редактора (cke

// prevent flashing of resizing by setting the content panel to zero height before it is resized
config.height = '0px';
config.width = '100%'; 
top) и панели содержимого (cke
// prevent flashing of resizing by setting the content panel to zero height before it is resized
config.height = '0px';
config.width = '100%'; 
contents). Высота .textPanel - это окружающий блок div, в который должен вписаться редактор. Я добавил 10 пикселей, потому что мне это нужно для моего макета.

Я думаю, что это может быть немного эффективнее (он инициирует изменение размера столько раз, сколько редакторов), но на данный момент он, наконец, работает безупречно во всех моих последних браузерах (ff, т.е. chrome и safari).

person klaaz    schedule 03.01.2013

Сначала добавьте функцию для изменения размера вашего редактора:

function resizeEditor() {

  var defaultHeight = 300;
  var newHeight = window.innerHeight-150; 
  var height = defaultHeight > newHeight ? defaultHeight: newHeight;

  CKEDITOR.instances.editor1.resize('100%',height);
}

Примечание: у меня работает 150, возможно, измените значение со 150 на более или менее.

Вызовите это из окна onresize Event:

window.onresize = function() {
  resizeEditor();
}

и добавьте первый вызов в конструктор вашего редактора:

CKEDITOR.replace('editor1',
  {  
    on:
    {
      instanceReady: function(ev)
      {
        setTimeout(resizeEditor, 500);
      }
    }
  });
person marco    schedule 07.04.2011

Мне удалось настроить высоту 100% через CSS:

  1. Настройте редактор с помощью config.height = '100%', даже если в документации указано, что это не поддерживается.
  2. Поместите это в свой CSS:
span.cke_wrapper cke_ltr,table.cke_editor, td.cke_contents, span.cke_skin_kama, span.cke_wrapper, span.cke_browser_webkit{
    height: 100%!important;
}

Я тестировал это с Chrome, Firefox и Safari, и он работал нормально. Поскольку это чистый CSS, высота будет регулироваться автоматически при изменении размера окна или соответствующего контейнера.

person jmanrubia    schedule 10.02.2012
comment
Попробуйте использовать полноэкранный режим. Как видите, это не лучшее решение. - person looper; 13.08.2012

В документации по ckeditor для CKEDITOR.config.height говорится, что они не поддерживают процентные единицы, например: 30%; однако есть тд с классом cke_contents. если вы установите для него высоту (с абсолютным значением, это будет работать).

Похоже, у ckeditor нет хорошего решения этой проблемы. Единственный другой способ, который я могу придумать, - это использовать javascript для изменения стиля в приведенном выше td.

person Lathan    schedule 30.12.2009
comment
Все остальное, что вам нужно знать об этой проблеме, находится здесь, docs.cksource. ru / ckeditor_api / symbols / - person kajo; 12.03.2011

Ни одно из вышеперечисленных решений не помогло мне установить высоту в процентах или без них. Проценты по-прежнему не поддерживаются, если вы не взломаете их одним из вышеперечисленных решений.

Как указано в документации, вы можете установить высоту и стиль css с помощью:

<head>
    <script type="text/javascript">
        CKEDITOR.config.height = 1000;
        CKEDITOR.config.contentsCss = '/css/yourstyle.css';
    </script>
</head>

http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.config.html#.height

person xtrm    schedule 19.10.2012

Поместите это свойство в свой файл конфигурации css:

.cke_reset{
    min-height: 200px;
}
person Gladson Roberto    schedule 16.08.2013

вот версия кода выше для додзё ... на случай, если кому-то интересно ...

var adjustEditor = function() {
  var editorNode = dom.byId('cke_messageEditor');
  console.log("editor node %s ", editorNode);
  var editorStyle = domStyle.getComputedStyle(editorNode);
  console.log("editor node %s and style %s", editorNode, editorStyle);
  var textEditHeight      = domGeom.getMarginBox(editorNode, editorStyle).h;

  var toolbarNode = dom.byId('cke_1_top');
  var toolbarStyle = domStyle.getComputedStyle(toolbarNode)
  var ckTopHeight = domGeom.getMarginBox(toolbarNode, toolbarStyle).h;

  var contentNode = dom.byId('cke_1_contents');
  var contentStyle = domStyle.getComputedStyle(contentNode)
  var ckContentsBox    = domGeom.getMarginBox(contentNode, contentStyle);
  console.log("text editor: %s, button bar: %s", textEditHeight, ckTopHeight);

  console.log("setting margin box to: %s ", JSON.stringify(ckContentsBox));
  ckContentsBox.h = textEditHeight - ckTopHeight;
  console.log("setting margin box to: %s ", JSON.stringify(ckContentsBox));

  domGeom.setMarginBox(contentNode, ckContentsBox, contentStyle);
}

// adjust editor immediately
CKEDITOR.on('instanceReady', adjustEditor);
// and again everytime the window is resized
on(window, "resize", adjustEditor);
person Pedro Guedes    schedule 24.02.2014

Я искал чистый способ заставить окно CKEditor иметь ту же высоту, что и текстовое поле, которое оно заменяет. Я использую Drupal, и вот как я это сделал ...

В своей теме я загружаю файл javascript (используя "scripts [] = default.js" в моем файле .info).

В этом файле у меня есть:

$(document).ready(function(){ 

    // Set CKEditor height
    if (typeof CKEDITOR!='undefined') {
        CKEDITOR.on( 'instanceReady', function( e ) {
            e.editor.element.show();
            var elHeight = $(e.editor.element.$).height();
            e.editor.element.hide();
            e.editor.resize('100%', elHeight, true);
        });
    }
}

Прелесть этого в том, что вы можете изменить высоту с помощью css.

Я менял settings.height через модуль wysiwyg в wysiwyg / editors / js / ckeditor-3.0.js

Drupal.wysiwyg.editor.attach.ckeditor = function(context, params, settings) {
    // Apply editor instance settings.
    CKEDITOR.config.customConfig = '';

    // Match the height of the replaced field
    settings.height = $('#' + params.field).height();
}

но это могло быть перезаписано во время обновлений, поэтому выбрал лучшее решение.

person Al.    schedule 31.08.2013

Я только что делал это в CKEditor4, не уверен, что это вам пригодится

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script src="ckeditor/ckeditor.js"></script>
		<!-- tested with CKEditor 4.5.3 (revision 6c70c82) -->
		<style type="text/css">
			.cke_1 {
				height: 100% !important;
				width: 100% !important;
				position: static;
				top: 0px;
				left: 0px;
				right: 0px;
				bottom: 0px;
			}
			.cke_inner {
				height: 100% !important;
				width: 100% !important;
				display: table !important;
			}			
			.cke_top { display: table-cell !important; }
			.cke_contents { height: 100% !important; display: table-row !important; }
			.cke_bottom { display: table-cell !important; }
			textarea.cktextarea {
				width: 100% !important;
				height: 100% !important;
			}
		</style>
		<script>
			CKEDITOR.config.width = '100%';
			CKEDITOR.config.height = '100%';
			CKEDITOR.plugins.registered['maximize'] = {
				init: function(editor) {
					var command = editor.addCommand('maximize', {
						modes: { wysiwyg:1, source:1 },
						exec: function(editor) {
							if (editor.container.getStyle('position') != 'fixed') {
								this.setState(CKEDITOR.TRISTATE_ON);
								editor.container.setStyle('position', 'fixed');;
							} else {
								this.setState(CKEDITOR.TRISTATE_OFF);
								editor.container.setStyle('position', 'static');
							}
						}
					});
					editor.ui.addButton('Maximize', { label: 'Maximize', command: 'maximize', toolbar: 'tools' });
				}
			}
		</script>
	</head>
	<body>
		<div style="background: darkgray; padding: 0.5em; display: inline-block; position: fixed; left: 20px; top: 20px; left: 20px; right: 20px; bottom: 20px;">
			<textarea name="editor1" id="editor1" class="cktextarea"></textarea>
			<script>CKEDITOR.replace('editor1');</script>
		</div>
    </body>
</html>

Если вы не используете плагин максимизации, большая часть javascript не нужна, я заменил функциональность этого плагина, потому что он нарушал новый CSS (и ломался сам по себе после того, как я установил все CSS! Important).

person netman    schedule 25.08.2015

Это решение для меня без jQuery, работающего в элементе управления C # WebBrowser, а также без вертикальной прокрутки при горизонтальном отображении.

<!DOCTYPE html>
<!--
Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
-->
<html>
<head>
	<meta charset="utf-8" http-equiv="X-UA-Compatible" content="IE=edge">
	<title>CKEditor Sample</title>
	<script src="../ckeditor.js"></script>
	<script src="js/sample.js"></script>
	<link rel="stylesheet" href="css/samples.css">
	<link rel="stylesheet" href="toolbarconfigurator/lib/codemirror/neo.css">
</head>
<body id="main">
	<div id="editor">
	</div>
	<script>
		initSample();

		CKEDITOR.on("instanceReady", function () { initFullSize(); });

		function initFullSize() {
			window.addEventListener("resize", onWindowResize);

			document.getElementById("main").style.minWidth = "970px";
			document.getElementById("cke_1_resizer").style.display = "none";
			document.getElementsByClassName("cke_inner cke_reset")[0].style.height = "100%";

			onWindowResize();
		}

		function onWindowResize() {
			document.getElementById("main").style.height = document.documentElement.clientHeight + "px";
			document.getElementById("cke_editor").style.height = document.documentElement.clientHeight - 3 + "px";
			document.getElementById("cke_1_contents").style.height = (document.documentElement.clientHeight - document.getElementById("cke_1_top").clientHeight - document.getElementById("cke_1_bottom").clientHeight - 3) + "px";
		}
	</script>
</body>
</html>

person Hrvoje Batrnek    schedule 19.02.2017