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

如何制作自定义Summernote按钮:实现链接类添加与选中文本动态包裹

实现Summernote自定义按钮:给元素加类/包裹选中文本

我之前也碰到过一模一样的问题!看官方指南只会加静态文本按钮,折腾了好半天才搞懂怎么处理动态选中的内容,不管是纯文本还是已有的HTML元素(比如链接)都能搞定。下面给你一步步拆解:

1. 注册自定义按钮到工具栏

首先得把自定义按钮加到Summernote的工具栏里,基础框架是这样的:

$(document).ready(function() {
  $('#summernote').summernote({
    // 把自定义按钮加入工具栏组
    toolbar: [
      ['style', ['bold', 'italic']],
      ['custom', ['customClassBtn']] // 自定义按钮组
    ],
    buttons: {
      customClassBtn: function(context) {
        const ui = $.summernote.ui;
        
        // 创建按钮UI
        const button = ui.button({
          contents: '<i class="fa fa-paint-brush"></i> 加自定义样式',
          tooltip: '为选中内容添加自定义类名',
          click: function() {
            // 点击按钮后执行核心逻辑
            applyCustomClass(context);
          }
        });
        
        return button.render(); // 返回按钮的DOM结构
      }
    }
  });
});

2. 核心逻辑:区分处理选中文本/已有元素

关键就是applyCustomClass函数,它会判断你选中的是纯文本还是已有的HTML元素(比如链接、段落),然后分别处理:

function applyCustomClass(context) {
  const $editor = context.layoutInfo.editor;
  const range = context.invoke('editor.getSelection');
  
  // 先判断有没有选中内容
  if (range.isCollapsed()) {
    alert('请先选中需要设置的内容或元素哦');
    return;
  }
  
  // 找到选中内容的最外层父元素
  let selectedElement = range.commonAncestorContainer;
  // 确保这个元素是编辑器内的有效元素
  while (selectedElement && !$editor.has(selectedElement).length) {
    selectedElement = selectedElement.parentNode;
  }
  
  // 情况1:选中的是HTML元素(比如链接<a>、段落<p>)
  if (selectedElement && selectedElement.nodeType === 1) {
    // 给元素添加自定义类名,这里换成你需要的类
    $(selectedElement).addClass('custom-target-class');
    
    // 如果你只想给特定元素(比如链接)加类,可以加判断:
    // if (selectedElement.nodeName === 'A') {
    //   $(selectedElement).addClass('custom-link-class');
    // }
  } 
  // 情况2:选中的是纯文本,包裹成指定标签并加类
  else {
    const selectedText = context.invoke('editor.getSelectedText');
    // 这里用span包裹,你也可以换成a、strong等标签
    const wrappedHtml = `<span class="custom-target-class">${selectedText}</span>`;
    context.invoke('editor.insertHTML', wrappedHtml);
  }
  
  // 操作完成后重新聚焦编辑器
  context.invoke('editor.focus');
}

3. 别忘了加自定义类的样式

最后要在CSS里定义你加的类的样式,不然看不到效果:

/* 自定义文本高亮样式 */
.custom-target-class {
  background-color: #fff3cd;
  padding: 2px 4px;
  border-radius: 2px;
}

/* 如果是给链接加的类 */
.custom-link-class {
  color: #dc3545;
  font-weight: bold;
  text-decoration: underline;
}

这样你的自定义按钮就既能给已插入的链接(或者其他HTML元素)添加类名,也能把选中的纯文本包裹起来加样式啦!

内容的提问来源于stack exchange,提问作者cdouble.bhuck

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 08:02:35