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

Bootstrap模态框/切换标签时TinyMCE工具栏抽屉无法自动隐藏

解决TinyMCE工具栏抽屉在Bootstrap模态框/标签页切换后残留的问题

问题场景

使用Bootstrap 4.3的模态框或标签页加载TinyMCE 6.7.0时,因空间有限点击Toggle Toolbar Drawer展开工具栏,但关闭模态框或切换标签页后,工具栏抽屉不会自动隐藏,仍悬浮在页面上,即使对应的编辑器已不可见。

已尝试以下代码但未解决:

if ( tinymce.activeEditor.queryCommandState('ToggleToolbarDrawer') ) {
  tinymce.activeEditor.execCommand('ToggleToolbarDrawer');
}

同时针对Bootstrap模态框的focusin处理代码也无效:

$(document).on("focusin", function(e) {
    if ($(e.target).closest(".tox-dialog").length) {
        e.stopImmediatePropagation();
    }
});

环境信息:

  • Chrome: 122.0.6261.128
  • Windows: 10
  • TinyMCE: 6.7.0
  • jQuery: 3.4.1
  • Bootstrap: 4.3

解决方案

1. Bootstrap模态框关闭时自动关闭抽屉

监听模态框的hidden.bs.modal事件(模态框完全关闭后触发),遍历所有TinyMCE编辑器实例,检查并关闭展开的工具栏抽屉:

// 替换#your-modal-id为你的模态框实际ID
$('#your-modal-id').on('hidden.bs.modal', function () {
  tinymce.each(tinymce.editors, function(editor) {
    if (editor.queryCommandState('ToggleToolbarDrawer')) {
      editor.execCommand('ToggleToolbarDrawer');
    }
    // 若模态框关闭后不再需要编辑器,可添加销毁逻辑
    // editor.destroy();
  });
});

2. Bootstrap标签页切换时自动关闭抽屉

监听标签页的shown.bs.tab事件(标签页切换完成后触发),判断编辑器所在容器是否在当前激活标签页内,不在则关闭抽屉:

$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
  const activeTabSelector = $(e.target).attr('href');
  tinymce.each(tinymce.editors, function(editor) {
    const isInActiveTab = $(editor.getElement()).closest(activeTabSelector).length > 0;
    if (!isInActiveTab && editor.queryCommandState('ToggleToolbarDrawer')) {
      editor.execCommand('ToggleToolbarDrawer');
    }
  });
});

注:需确保标签的href属性与对应内容容器的ID一致(如标签href为#tab-content-1,内容容器ID为tab-content-1)。

3. 通用容器隐藏监听

若编辑器所在容器可能通过其他方式隐藏(如折叠面板),可监听容器的隐藏事件,针对性处理:

// 替换.editor-container为编辑器所在容器的选择器
$('.editor-container').on('hide.bs.collapse hidden.bs.modal', function() {
  const textareaId = $(this).find('textarea').attr('id');
  const editor = tinymce.get(textareaId);
  if (editor && editor.queryCommandState('ToggleToolbarDrawer')) {
    editor.execCommand('ToggleToolbarDrawer');
  }
});

失效原因分析

  • tinymce.activeEditor不可靠:页面存在多个编辑器或编辑器失焦时,activeEditor可能指向错误实例或为null,遍历所有编辑器更稳妥。
  • 事件触发时机错误:之前未绑定到模态框完全关闭、标签页切换完成的正确事件上,导致代码未在合适时机执行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 13:23:34