如果今天想要让ckeditor的输入部分,能够根据输入内容的多寡来自适应高度
可以客製化ckeditor中的plugins
https://ckeditor.com/cke4/builder
但是我要使用时遇到LTS - Long Term Support不相容的问题
看了一下,可能有的plugins是需要付费的(Extended Support Model Package)
当然如果这部分我弄错了可以在下方指正我
因此我决定使用js来监听用户的特定操作来改变输入栏位的高度
首先在html中新增一个textarea并设定id<textarea name="content" id="my_editor"></textarea>
因为我是直接把ckeditor的档案都放在我专案内部了,所以在js档中引入ckeditor.jsimport * as name from "../ckeditor/ckeditor.js"; // 引入js内容
使用replace方法,让CKEditor instance去取代原有的DOM,并且设定初始高度let my_editor = CKEDITOR.replace("my_editor", { height: "500px",});
图源:https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR.html#method-replace
function adjustEdtiorHeight(editor) { let contentHeight = editor.document.getBody().$.scrollHeight; if (contentHeight > 500) { editor.resize("100%", contentHeight); } else { editor.resize("100%", 500); }}
editor.document.getBody()可以获取body元素


my_editor.on("contentDom", function () { // 监听输入事件 my_editor.document.on("inpput", function () { adjustEdtiorHeight(my_editor); }); // 监听贴上事件 my_editor.document.on("paste", function () { adjustEdtiorHeight(my_editor); }); my_editor.document.on("keyup", function (event) { // 监听enter事件 if (event.data.getKeystroke() === 13) { adjustEdtiorHeight(my_editor); // 监听删除键事件 } else if (event.data.getKeystroke() === 8) { adjustEdtiorHeight(my_editor); } });});
首先看到editor.on可以监听特定event
图源:https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_editor.htmlcontentDom event 会等DOM结构準备好时才触发

图源:https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_editor.html#event-contentDom
都设置好后,当你做出以上操作时editor就能自适应高度啦