Jodit编辑器自定义按钮:如何始终在编辑器开头插入HTML
解决方案
要实现将自定义HTML插入到Jodit编辑器开头,有两种可靠的实现方式:
方法1:先定位光标到编辑器开头,再插入HTML
通过Jodit的Selection API将光标移到编辑器内容最前端,再调用insertHTML(),插入的内容就会自动出现在开头。修改后的exec函数代码如下:
exec: function (editor) { const contentContainer = editor.getEditorElement(); // 定位光标到编辑器内容开头 if (contentContainer.firstChild) { editor.s.setCursorBefore(contentContainer.firstChild); } else { editor.s.setCursorStart(contentContainer); } // 插入自定义HTML editor.s.insertHTML("<hr /><b>"+new Date().toDateString()+"</b><br />start typing here<br />"); }
方法2:直接拼接HTML到现有内容前
如果不需要保留原光标位置,可以直接获取编辑器当前内容,把新HTML拼接到前面后重新设置:
exec: function (editor) { const customHTML = "<hr /><b>"+new Date().toDateString()+"</b><br />start typing here<br />"; // 将新HTML添加到现有内容最前面 editor.setHTML(customHTML + editor.getHTML()); }
完整修改后的代码示例
var editor = Jodit.make('#investigation', { buttons: [ 'insertDate' ], controls: { insertDate: { name: 'insertDate', iconURL: '../../../images/icons/jodit/calendar.png', exec: function (editor) { const contentContainer = editor.getEditorElement(); if (contentContainer.firstChild) { editor.s.setCursorBefore(contentContainer.firstChild); } else { editor.s.setCursorStart(contentContainer); } editor.s.insertHTML("<hr /><b>"+new Date().toDateString()+"</b><br />start typing here<br />"); } } } });
关键API说明
editor.getEditorElement():获取Jodit编辑器的内容容器(iframe模式对应内部body元素,inline模式对应绑定的DOM元素)editor.s.setCursorBefore(element):将光标移动到指定元素的前方editor.s.setCursorStart(element):将光标移动到指定元素的起始位置(适配内容为空的场景)
内容的提问来源于stack exchange,提问作者Dries
相关产品推荐
相关产品推荐

