You need to enable JavaScript to run this app. Codemirror编辑器关闭标签未渲染样式,点击输出到iframe功能问题求助
优惠活动
大模型
产品
解决方案
定价
更多

Codemirror编辑器关闭标签未渲染样式,点击输出到iframe功能问题求助

问题根因

关闭标签无法正常应用高亮样式的核心原因是CodeMirror初始化时未指定对应语法模式,编辑器无法正确识别HTML标签结构导致。同时当前向iframe写入内容的方式存在结构兼容问题,可同步优化。

解决方案

  1. 给CodeMirror初始化配置新增mode: "htmlmixed"参数,启用已引入的HTML混合语法解析模式,即可正常识别开闭标签、应用对应高亮样式。
  2. 优化iframe内容写入逻辑,直接写入整个iframe文档,避免只替换body导致的HTML结构丢失问题。

修正后的核心代码

var editor = CodeMirror(document.getElementById("codeeditor"), {
    value: "<html>\n<body class=\"fdf\">\n<h1>Hello world</h1>\n<button type=\"button\" disabled>Click Me!</button>\n</body>\n</html>",
    mode: "htmlmixed", // 新增该行配置
    theme: "neo",
    lineNumbers: true,
    matchBrackets: true
});

// 优化iframe写入逻辑
$("button").click(function(){     
  const iframeDoc = $("iframe")[0].contentDocument;
  iframeDoc.open();
  iframeDoc.write(editor.getValue());
  iframeDoc.close();
})

将原有代码的对应部分替换为上述内容即可正常运行。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 03:45:02