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

如何制作类似Codepen的文本编辑器并实现明暗切换与语法高亮

解决方案

你已经引入了CodeMirror依赖,可直接基于现有代码调整实现两个缺失功能,无需额外引入外部资源:

功能1:语法高亮实现

你当前没有对引入的CodeMirror进行初始化,仍然使用原生textarea渲染代码,直接替换初始化逻辑即可获得语法高亮能力:

修改后的JS代码

// 初始化三个CodeMirror编辑器,替代原生textarea
const htmlEditor = CodeMirror.fromTextArea(document.getElementById("html"), {
  mode: "xml",
  lineNumbers: true,
  theme: "default"
});
const cssEditor = CodeMirror.fromTextArea(document.getElementById("css"), {
  mode: "css",
  lineNumbers: true,
  theme: "default"
});
const jsEditor = CodeMirror.fromTextArea(document.getElementById("js"), {
  mode: "javascript",
  lineNumbers: true,
  theme: "default"
});

// 编译逻辑修改为从CodeMirror实例取内容
function compile(){
  const code = document.getElementById("code").contentWindow.document;
  const htmlVal = htmlEditor.getValue();
  const cssVal = cssEditor.getValue();
  const jsVal = jsEditor.getValue();
  code.open();
  code.writeln(htmlVal + "<style>" + cssVal + "</style>" + "<script>" + jsVal + "<\/script>");
  code.close();
}

// 监听CodeMirror内容变化实时编译
[htmlEditor, cssEditor, jsEditor].forEach(editor => {
  editor.on("change", compile);
});

compile();

功能2:明暗模式切换实现

第一步:HTML新增切换按钮

在header标签内新增切换按钮:

<header id="playground_header">
  <button id="themeToggle" style="position:absolute;left:20px;padding:8px 12px;border:none;border-radius:4px;cursor:pointer;">切换到亮色模式</button>
  <h1>Coding Playground | #Programmer</h1>
</header>

第二步:CSS新增明暗主题变量

在原有CSS末尾新增:

/* 亮色主题变量 */
.page-wrap.light .CodeMirror {
  background: #ffffff;
  color: #24292e;
}
.page-wrap.light .CodeMirror-gutters {
  background: #f6f8fa;
  border-right: 1px solid #e1e4e8;
}
.page-wrap.light #code {
  background: #ffffff;
}
.page-wrap.light header#playground_header {
  background: #f6f8fa;
}
.page-wrap.light header#playground_header h1 {
  color: #24292e;
}
.page-wrap.light #coding_area {
  border-color: #e1e4e8;
}
.page-wrap.light div#coding_area > div {
  border-left-color: #e1e4e8;
}

第三步:JS新增切换逻辑

在原有JS末尾新增:

// 明暗主题切换逻辑
const themeToggle = document.getElementById('themeToggle');
const pageWrap = document.querySelector('.page-wrap');
let isDark = true;

themeToggle.addEventListener('click', () => {
  isDark = !isDark;
  [htmlEditor, cssEditor, jsEditor].forEach(editor => {
    editor.setOption("theme", isDark ? "default" : "default");
  });
  if(isDark) {
    pageWrap.classList.remove('light');
    themeToggle.textContent = '切换到亮色模式';
  } else {
    pageWrap.classList.add('light');
    themeToggle.textContent = '切换到暗色模式';
  }
  compile();
});

调整完成后即可同时具备语法高亮、实时预览、明暗模式切换三个核心功能。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 14:57:04