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

使用Prism.js实现语法高亮时出现多余换行问题求助

解决连续换行时Prism.js高亮内容换行翻倍问题

问题根源

  1. 错误获取了<pre>元素的文本内容,而非真正可编辑的<code>标签,导致<pre>本身的空白换行被混入输入内容,叠加后造成换行翻倍。
  2. 高亮结果直接放入<div>容器,未使用Prism预期的<pre><code>结构,换行处理逻辑冲突。

分步解决方案

1. 修正内容获取目标

修改JavaScript,直接选中可编辑的<code>元素,同时将高亮结果包裹在<pre><code>中,匹配Prism的渲染结构:

const codeElement = document.querySelector('#code code');
const highlightElement = document.getElementById('highlight');

function updateHighlight() {
    const code = codeElement.innerText;
    const highlightedCode = `<pre><code>${Prism.highlight(code, Prism.languages.html, 'html')}</code></pre>`;
    highlightElement.innerHTML = highlightedCode;
}

codeElement.addEventListener('input', updateHighlight);

2. 统一上下层样式

调整#highlight的CSS,移除偏移并适配内部的<pre><code>结构,确保和可编辑区域样式完全对齐:

#highlight {
    position: absolute;
    left: 0%;
    top: 0%;
    z-index: 0;
    width: 100%;
    height: 100%;
    background-color: white;
    font-size: 14px;
    color: #333;
    line-height: 1.5;
    white-space: pre-wrap;
    overflow: auto;
    padding: 0;
    margin: 0;
}

#highlight pre,
#highlight code {
    width: 100%;
    height: 100%;
    padding-left: 5px;
    margin: 0;
    font-family: 'Courier New', Courier, monospace;
    font-size: 14px;
    line-height: 1.5;
    white-space: pre-wrap;
}

3. 清理HTML多余空白

移除<pre>和<code>之间的缩进换行,避免初始内容混入多余空白:

<div id="codeContainer">
    <div id="highlight"></div>
    <pre id="code"><code contenteditable="true"></code></pre>
</div>

效果验证

修改后,输入连续换行时,下层高亮内容的换行将和输入完全一致,不会出现翻倍情况,同时上下层视觉对齐也更准确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 01:57:54