模态框与textarea中CKEditor5内联编辑器工具栏不显示求助
解决模态框中CKEditor5内联编辑器工具栏不显示的问题
问题根源是模态框初始化时处于隐藏状态,CKEditor无法正确计算工具栏的位置和渲染状态,因此必须等模态框完全显示后再初始化编辑器,或者在显示后触发工具栏的刷新。
以下是针对常见场景的可行方案:
方案1:Bootstrap模态框场景
利用Bootstrap模态框的shown.bs.modal事件(模态框完全显示后触发)初始化编辑器,同时处理复用和内存泄漏问题:
<!-- Bootstrap模态框示例 --> <div class="modal fade" id="contentModal" tabindex="-1" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">编辑内容</h5> <button type="button" class="btn-close" data-bs-dismiss="modal"></button> </div> <div class="modal-body"> <!-- 编辑器容器 --> <div class="col-sm-12" id="modalD"></div> </div> </div> </div> </div> <script src="https://cdn.ckeditor.com/ckeditor5/18.0.0/inline/ckeditor.js"></script> <script> let editorInstance = null; // 模态框显示后初始化/刷新编辑器 document.getElementById('contentModal').addEventListener('shown.bs.modal', async () => { if (!editorInstance) { // 首次显示时初始化编辑器 try { editorInstance = await InlineEditor.create(document.querySelector('#modalD')); } catch (err) { console.error(err); } } else { // 复用编辑器时,强制刷新工具栏 editorInstance.editing.view.focus(); editorInstance.ui.view.toolbarView.render(); } }); // 模态框隐藏时销毁编辑器,避免内存泄漏 document.getElementById('contentModal').addEventListener('hidden.bs.modal', () => { if (editorInstance) { editorInstance.destroy(); editorInstance = null; } }); </script>
方案2:自定义模态框场景
如果是自己实现的模态框,需要在模态框设置为可见后,等待DOM重绘完成再初始化/刷新编辑器:
// 显示模态框的函数 function openCustomModal() { const modal = document.getElementById('modalContainer'); modal.style.display = 'block'; // 显示模态框 // 等待DOM重绘完成(100ms足够适配多数场景) setTimeout(async () => { if (!editorInstance) { editorInstance = await InlineEditor.create(document.querySelector('#modalD')); } else { editorInstance.editing.view.focus(); editorInstance.ui.view.toolbarView.render(); } }, 100); } // 隐藏模态框时销毁编辑器 function closeCustomModal() { const modal = document.getElementById('modalContainer'); modal.style.display = 'none'; if (editorInstance) { editorInstance.destroy(); editorInstance = null; } }
针对textarea的补充说明
InlineEditor是用于**内联可编辑元素(如div)**的编辑器,如果需要在textarea上集成CKEditor,应该使用ClassicEditor替换,同样遵循"可见后初始化"的原则:
<textarea id="modalTextarea" class="col-sm-12"></textarea> <script> document.getElementById('contentModal').addEventListener('shown.bs.modal', async () => { await ClassicEditor.create(document.querySelector('#modalTextarea')) .catch(err => console.error(err)); }); </script>
内容的提问来源于stack exchange,提问作者Ruman Ali
相关产品推荐
相关产品推荐

