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

GrapesJS如何打开包含源代码的view-code模态弹窗?

GrapesJS 实现点击按钮弹出代码查看模态框

你不需要从零开发模态框逻辑,直接用GrapesJS内置的Modal API配合代码获取方法就能实现和官方Demo一致的效果。

直接可用的命令实现代码

把你之前写的export命令替换成下面的代码即可:

editor.Commands.add('export', {
  run: (editor) => {
    // 取出编辑器当前的HTML、CSS内容
    const pageHtml = editor.getHtml();
    const pageCss = editor.getCss();
    // 组装模态框内容,做HTML/CSS切换Tab和代码展示区
    const content = `
    <div style="margin-bottom: 12px; display: flex; gap: 8px;">
      <button class="code-tab" data-code="full" style="padding: 6px 12px; border: none; border-radius: 4px; cursor: pointer; background: #4b9bff; color: #fff;">完整代码</button>
      <button class="code-tab" data-code="html" style="padding: 6px 12px; border: 1px solid #ddd; border-radius: 4px; cursor: pointer;">HTML</button>
      <button class="code-tab" data-code="css" style="padding: 6px 12px; border: 1px solid #ddd; border-radius: 4px; cursor: pointer;">CSS</button>
    </div>
    <textarea id="gjs-export-code" style="width: 100%; min-height: 380px; padding: 10px; font-family: monospace; border: 1px solid #ddd; border-radius: 4px; resize: vertical;"><!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <style>
${pageCss}
  </style>
</head>
<body>
${pageHtml}
</body>
</html></textarea>
    `;
    // 调用内置模态框
    const modal = editor.Modal;
    modal.setTitle('导出代码');
    modal.setContent(content);
    modal.open();

    // 绑定Tab切换逻辑
    const codeTextarea = modal.getContentEl().querySelector('#gjs-export-code');
    const tabBtns = modal.getContentEl().querySelectorAll('.code-tab');
    tabBtns.forEach(btn => {
      btn.addEventListener('click', () => {
        // 重置所有按钮样式
        tabBtns.forEach(b => {
          b.style.background = '#fff';
          b.style.color = '#000';
          b.style.border = '1px solid #ddd';
        });
        // 高亮当前选中按钮
        btn.style.background = '#4b9bff';
        btn.style.color = '#fff';
        btn.style.border = 'none';
        // 切换对应代码内容
        const type = btn.dataset.code;
        if(type === 'full') {
          codeTextarea.value = `<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <style>
${pageCss}
  </style>
</head>
<body>
${pageHtml}
</body>
</html>`;
        } else if(type === 'html') {
          codeTextarea.value = pageHtml;
        } else {
          codeTextarea.value = pageCss;
        }
      })
    })
  }
})

更省事的方案

如果不想自己写模态框内容和交互,可以直接安装官方导出插件grapesjs-plugin-export,安装完成后在编辑器初始化配置里引入插件,然后把面板里export按钮的command属性值改成插件自带的gjs-export即可,不需要自己写命令逻辑,效果和官方Demo完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 04:03:24