如何为Suneditor添加自定义按钮并在光标位置插入指定HTML
Suneditor自定义按钮插入指定HTML解决方案
你之前的代码是实现**范围格式(给选中内容添加带类的div)**的功能,要改成点击按钮在光标位置插入<p>welcome!</p>,需要调整插件的核心逻辑,以下是修改后的完整代码:
var plugin_command = { name: 'insertWelcome', display: 'command', title: '插入欢迎文本', buttonClass: '', innerHTML: '<i class="fas fa-carrot"></i>', add: function(core, targetElement) { core.context.insertWelcome = { targetButton: targetElement }; }, active: function(element) { this.util.removeClass(this.context.insertWelcome.targetButton, 'active'); return false; }, action: function() { const core = this; // 定义要插入的HTML代码 const insertHtml = '<p>welcome!</p>'; // 保存当前光标选区 core.saveRange(); // 插入指定HTML core.insertHTML(insertHtml); // 恢复选区并刷新编辑器状态 core.restoreRange(); core.focus(); core.eventModified(); } }
关键修改说明:
- 简化
add方法:移除了原来的rangeTag相关逻辑,只保留按钮引用,因为不需要给选中内容添加格式标签 - 调整
active方法:因为这个按钮不需要根据选中内容切换激活状态,所以直接移除按钮的active类并返回false(如果不需要该方法可以直接删除) - 重写
action方法:使用Suneditor内置的API完成插入操作:saveRange():保存当前光标位置,避免插入后光标丢失insertHTML():直接插入指定的HTML代码restoreRange()+focus():恢复光标并聚焦编辑器eventModified():触发编辑器的修改事件,确保内容变更被正确识别
插件注册方式
初始化编辑器时,将自定义插件加入plugins数组,并把按钮名称添加到buttonList中:
SunEditor.create('#suneditor', { plugins: [plugin_command], buttonList: [ ['insertWelcome'], // 加入自定义按钮 ['undo', 'redo'], ['bold', 'italic', 'underline'], // 其他你需要的按钮... ] });
内容的提问来源于stack exchange,提问作者Kazu
相关产品推荐
相关产品推荐

