使用原生js控制ckeditor自适应高度

如果今天想要让ckeditor的输入部分,能够根据输入内容的多寡来自适应高度
可以客製化ckeditor中的plugins
https://ckeditor.com/cke4/builder

http://img2.58codes.com/2024/20161866k29wq5r3k2.png

但是我要使用时遇到LTS - Long Term Support不相容的问题
看了一下,可能有的plugins是需要付费的(Extended Support Model Package)
当然如果这部分我弄错了可以在下方指正我

因此我决定使用js来监听用户的特定操作来改变输入栏位的高度

首先在html中新增一个textarea并设定id
<textarea name="content" id="my_editor"></textarea>
因为我是直接把ckeditor的档案都放在我专案内部了,所以在js档中引入ckeditor.js
import * as name from "../ckeditor/ckeditor.js"; // 引入js内容
使用replace方法,让CKEditor instance去取代原有的DOM,并且设定初始高度
let my_editor = CKEDITOR.replace("my_editor", {  height: "500px",});

http://img2.58codes.com/2024/20161866nZNlQ02APA.png
图源:https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR.html#method-replace

设置调整editor高度的方法,如果发现内容元素高于500时,就resize editor的高度,反之则维持
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元素
http://img2.58codes.com/2024/20161866C4vW1hsjLv.png我们接下来来看他内部的属性,看到在$ object下有scrollHeight属性,就是我们要的高度,不过不含margin跟border
http://img2.58codes.com/2024/20161866BDShHGXvOp.png
http://img2.58codes.com/2024/20161866MKNqsHz4GJ.pngresize方法可参考https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_editor.html#method-resize设置不同的监听事件
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
http://img2.58codes.com/2024/20161866y04Co8fb7q.png
图源:https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_editor.htmlcontentDom event 会等DOM结构準备好时才触发
http://img2.58codes.com/2024/20161866hQ4GbJ3xMh.png
图源:https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_editor.html#event-contentDom

都设置好后,当你做出以上操作时editor就能自适应高度啦


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章