如何在textarea中通过onkeyup事件实现类在线编译器的代码高亮
实现textarea实时代码高亮(无编译在线编译器效果)
方案一:使用code-prettify实现
textarea本身无法渲染高亮样式,需要搭配<pre><code>容器展示高亮结果,同时让输入内容实时同步到该容器中。
1. 页面结构
<div class="editor-container"> <!-- 输入用的textarea --> <textarea id="codeInput" onkeyup="updateHighlight()"></textarea> <!-- 展示高亮代码的容器 --> <pre class="prettyprint"><code id="highlightedCode" class="prettyprint"></code></pre> </div> <!-- 引入code-prettify库 --> <script src="https://cdn.jsdelivr.net/gh/google/code-prettify@master/loader/run_prettify.js"></script>
2. 样式调整(可选,优化编辑器观感)
.editor-container { position: relative; width: 800px; height: 400px; } #codeInput, #highlightedCode { position: absolute; top: 0; left: 0; width: 100%; height: 100%; padding: 10px; font-family: monospace; font-size: 14px; border: 1px solid #ccc; } #codeInput { background: transparent; color: transparent; caret-color: #333; /* 保证光标可见 */ z-index: 1; } #highlightedCode { z-index: 0; pointer-events: none; /* 避免点击干扰输入 */ white-space: pre-wrap; word-wrap: break-word; }
3. 同步与高亮逻辑
function updateHighlight() { const input = document.getElementById('codeInput'); const codeElement = document.getElementById('highlightedCode'); // 转义HTML特殊字符,防止页面结构被破坏及XSS风险 const escapedCode = input.value .replace(/&/g, '&') .replace(/</g, '<') .replace(/>/g, '>') .replace(/"/g, '"') .replace(/'/g, '''); codeElement.textContent = escapedCode; // 重新触发代码高亮 PR.prettyPrint(); } // 初始化触发,处理初始内容或粘贴的代码 updateHighlight();
方案二:使用Prism.js(更现代的替代方案)
Prism.js是轻量且活跃的高亮库,语法支持更丰富,实现逻辑类似:
1. 页面结构
<div class="editor-container"> <textarea id="codeInput" onkeyup="updateHighlight()"></textarea> <pre><code id="highlightedCode" class="language-javascript"></code></pre> </div> <!-- 引入Prism的样式和核心库 --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/prismjs@1/themes/prism.min.css"> <script src="https://cdn.jsdelivr.net/npm/prismjs@1/prism.min.js"></script>
2. 同步与高亮逻辑
// 防抖函数优化性能,减少频繁触发高亮 function debounce(func, delay = 100) { let timer; return function() { clearTimeout(timer); timer = setTimeout(() => func.apply(this, arguments), delay); }; } const updateHighlight = debounce(function() { const input = document.getElementById('codeInput'); const codeElement = document.getElementById('highlightedCode'); // 转义特殊字符 const escapedCode = input.value .replace(/&/g, '&') .replace(/</g, '<') .replace(/>/g, '>'); codeElement.textContent = escapedCode; // 重新执行高亮 Prism.highlightElement(codeElement); }); // 初始化 updateHighlight();
关键注意事项
- 特殊字符转义:必须处理输入内容中的HTML特殊字符,否则会破坏页面结构或引发安全问题。
- 性能优化:使用防抖函数降低高亮触发频率,避免输入时出现卡顿。
- 语言指定:使用Prism时,需给code标签添加对应
language-xxx类(如language-python),确保语法高亮精准。
内容的提问来源于stack exchange,提问作者Steve
相关产品推荐
相关产品推荐

