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

React中Jodit编辑器自定义按钮全区域点击打开下拉菜单的实现

问题描述

在React应用中使用Jodit编辑器时,已实现自定义工具栏按钮插入文本片段的功能。该按钮带有自定义图标和右侧Chevron,但目前仅点击Chevron可展开/收起下拉菜单,希望改为类似默认段落按钮的效果——点击按钮任意区域均可打开下拉菜单。

现有自定义按钮配置如下:

{
  name: "Textbausteine",
  icon: "dots",
  list: textModules.map((module) => module.name),
  tooltip: "Textbaustein einfügen",
  exec: (
    jodit: IJodit,
    _current: Nullable<Node>,
    options: {
      button: IToolbarButton;
      control: IControlType<IJodit>;
      originalEvent: Event;
    },
  ) => {
    if (options.control.args) {
      const moduleIndex = options.control.args?.at(1);
      jodit.selection.insertHTML(textModules[moduleIndex].content);
    } else {
      // 尝试打开下拉菜单,但jodit.selection.expandSelection()无效果
    }
  },
}
解决方案

要实现点击按钮任意区域都展开下拉菜单,无需使用jodit.selection.expandSelection(),可以通过以下两种方式实现:

方法1:在exec方法中主动触发下拉菜单切换

当点击按钮主体(未选择下拉选项时),直接调用按钮实例的togglePopup方法来切换下拉菜单的显示状态:

exec: (
  jodit: IJodit,
  _current: Nullable<Node>,
  options: {
    button: IToolbarButton;
    control: IControlType<IJodit>;
    originalEvent: Event;
  },
) => {
  if (options.control.args) {
    const moduleIndex = options.control.args?.at(1);
    jodit.selection.insertHTML(textModules[moduleIndex].content);
  } else {
    // 切换下拉菜单的显示/隐藏状态
    options.button.togglePopup();
  }
}

方法2:将控件类型设置为"select"

如果希望按钮行为完全匹配默认段落按钮,可直接给控件添加type: "select"配置,Jodit会自动处理点击按钮任意区域展开下拉的逻辑,无需手动编写展开代码:

{
  name: "Textbausteine",
  icon: "dots",
  type: "select", // 指定为选择器类型控件
  list: textModules.map((module) => module.name),
  tooltip: "Textbaustein einfügen",
  exec: (
    jodit: IJodit,
    _current: Nullable<Node>,
    options: {
      button: IToolbarButton;
      control: IControlType<IJodit>;
      originalEvent: Event;
    },
  ) => {
    if (options.control.args) {
      const moduleIndex = options.control.args?.at(1);
      jodit.selection.insertHTML(textModules[moduleIndex].content);
    }
  },
}

内容的提问来源于stack exchange,提问作者Svenja Süttenbach

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 08:35:30