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

如何在TinyMCE中设置初始DOM包装div且获取内容时排除它们?

实现方案

1. 初始化时自动添加嵌套包装结构

在TinyMCE的初始化配置中,通过setup钩子监听init事件,动态创建所需的包装div,并将编辑器原有内容(或空白区域)移入内层容器:

tinymce.init({
  selector: '#myTextarea',
  setup: function(editor) {
    editor.on('init', function() {
      // 创建外层包装div
      const wrapper = editor.dom.create('div', { class: 'myWrapper' });
      // 创建内层用户输入容器
      const container = editor.dom.create('div', { class: 'myWrapperContainer' });

      // 将编辑器body内的原有内容转移到内层容器
      while (editor.getBody().firstChild) {
        container.appendChild(editor.getBody().firstChild);
      }

      // 将嵌套结构插入编辑器body
      editor.getBody().appendChild(wrapper);
      wrapper.appendChild(container);

      // 设置默认光标位置在内层容器,确保用户输入直接进入目标区域
      editor.selection.select(container, true);
      editor.selection.collapse(false);
    });
  },
  // 可选:为包装结构添加样式
  content_style: `
    .myWrapper {
      padding: 20px;
      background-color: #f8f9fa;
    }
    .myWrapperContainer {
      background-color: #ffffff;
      padding: 15px;
      border-radius: 4px;
      box-shadow: 0 1px 3px rgba(0,0,0,0.1);
    }
  `
});

2. 获取内容时自动过滤外层包装div

通过监听beforeGetContent事件,拦截默认的内容获取逻辑,直接返回内层容器的HTML内容:

tinymce.init({
  // 其他配置...
  setup: function(editor) {
    // 上面的init事件代码...

    // 拦截getContent(),返回内层容器内容
    editor.on('beforeGetContent', function(e) {
      const container = editor.dom.select('div.myWrapperContainer')[0];
      if (container) {
        e.content = container.innerHTML;
      }
    });
  }
});

之后直接调用原有代码即可得到纯净的用户输入内容:

var userContent = tinymce.get("myTextarea").getContent();

备选方案:手动获取内层内容

如果不需要全局拦截,也可以在需要获取内容时直接定位到内层容器:

function getUserInput() {
  const editor = tinymce.get('myTextarea');
  const container = editor.dom.select('div.myWrapperContainer')[0];
  return container ? container.innerHTML : editor.getContent();
}

// 使用示例
var userContent = getUserInput();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 15:01:11