You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为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完成插入操作:
    1. saveRange():保存当前光标位置,避免插入后光标丢失
    2. insertHTML():直接插入指定的HTML代码
    3. restoreRange() + focus():恢复光标并聚焦编辑器
    4. eventModified():触发编辑器的修改事件,确保内容变更被正确识别

插件注册方式

初始化编辑器时,将自定义插件加入plugins数组,并把按钮名称添加到buttonList中:

SunEditor.create('#suneditor', {
    plugins: [plugin_command],
    buttonList: [
        ['insertWelcome'], // 加入自定义按钮
        ['undo', 'redo'],
        ['bold', 'italic', 'underline'],
        // 其他你需要的按钮...
    ]
});

内容的提问来源于stack exchange,提问作者Kazu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 17:22:14