
在原生 HTML 中,textarea 不支持内联 HTML 渲染,因此无法直接通过 innerHTML 插入 <span> 实现语法高亮;正确方案是用 contenteditable 的 <div> 替代,并结合 DOM 操作安全插入带样式的片段。
在原生 html 中,textarea 不支持内联 html 渲染,因此无法直接通过 `innerhtml` 插入 `` 实现语法高亮;正确方案是用 `contenteditable` 的 ` 实现动态语法高亮的核心前提,是放弃使用 <textarea>——因为它仅接受纯文本,innerHTML 赋值会被忽略或转义,上述示例代码在 textarea 上实际无效。正确做法是采用 contenteditable="true" 的容器(如 <div>),并借助浏览器原生的 Range 和 Selection API 精准操作文本节点。 以下是一个健壮、可复用的高亮函数示例: ⚠️ 注意事项: 综上,动态 span 插入完全可行,但必须建立在语义正确的可编辑容器之上——这是实现前端轻量级语法高亮的基石。function highlightText(
element: HTMLElement,
start: number,
end: number,
color: string = '#d32f2f',
className: string = 'syntax-highlight'
) {
// 清除已有高亮(可选)
element.querySelectorAll(`.${className}`).forEach(el => {
el.replaceWith(...el.childNodes);
});
const textNode = element.firstChild as Text | null;
if (!textNode || !textNode.textContent) return;
const fullText = textNode.textContent;
if (start < 0 || end > fullText.length || start > end) return;
// 创建文档片段用于安全插入
const fragment = document.createDocumentFragment();
// 插入前置文本
if (start > 0) {
fragment.appendChild(document.createTextNode(fullText.substring(0, start)));
}
// 插入高亮 span
const span = document.createElement('span');
span.className = className;
span.style.color = color;
span.textContent = fullText.substring(start, end);
fragment.appendChild(span);
// 插入后置文本
if (end < fullText.length) {
fragment.appendChild(document.createTextNode(fullText.substring(end)));
}
// 替换整个文本节点
element.textContent = ''; // 清空以避免残留
element.appendChild(fragment);
}
// 使用示例
const editor = document.getElementById('code-editor') as HTMLElement;
editor.contentEditable = 'true';
editor.innerHTML = 'function hello() { console.log("world"); }';
// 高亮前10个字符(如 "function h")
highlightText(editor, 0, 10, '#e53e3e');

















