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

如何在HTML/CSS/JSS中实现VS Code风格的垂直行号?

实现VS Code风格的垂直行号功能

核心思路

将行号区域与代码编辑区域拆分为两个独立容器,保持两者行高、字体完全匹配,同步滚动状态,动态根据编辑内容生成对应行号。

具体实现步骤

1. 布局结构

用弹性布局让行号容器与编辑容器并排,行号容器固定宽度,编辑容器占满剩余空间:

<div class="editor-container">
  <div class="line-numbers" id="lineNumbers"></div>
  <textarea class="code-editor" id="codeEditor"></textarea>
</div>

2. 样式对齐

通过CSS确保行号与代码行高度一致,行号区域设为不可选中,用背景色区分:

.editor-container {
  display: flex;
  font-family: 'Consolas', 'Monaco', monospace;
}
.line-numbers {
  width: 48px;
  background-color: #f6f6f6;
  padding: 8px 6px 8px 0;
  text-align: right;
  user-select: none;
  line-height: 1.6;
  font-size: 14px;
}
.code-editor {
  flex: 1;
  border: none;
  outline: none;
  resize: none;
  padding: 8px;
  line-height: 1.6;
  font-size: 14px;
  background-color: #ffffff;
}

3. 动态生成与滚动同步

用JavaScript监听编辑内容变化和滚动事件,实时更新行号并同步滚动位置:

const codeEditor = document.getElementById('codeEditor');
const lineNumbers = document.getElementById('lineNumbers');

// 更新行号列表
function refreshLineNumbers() {
  const lineCount = codeEditor.value.split('\n').length;
  let numberHtml = '';
  for (let i = 1; i <= lineCount; i++) {
    numberHtml += `<div>${i}</div>`;
  }
  lineNumbers.innerHTML = numberHtml;
  // 同步滚动位置
  lineNumbers.scrollTop = codeEditor.scrollTop;
}

// 绑定事件
codeEditor.addEventListener('input', refreshLineNumbers);
codeEditor.addEventListener('scroll', () => {
  lineNumbers.scrollTop = codeEditor.scrollTop;
});

// 初始化行号
refreshLineNumbers();

4. 进阶优化点

  • 选中行高亮:监听编辑器选区变化,计算选中行范围,给对应行号添加高亮样式
  • 性能优化:内容变化时仅更新新增/删除的行号,避免全量重绘
  • 适配复杂场景:处理软换行、不同字体行高差异,确保行号始终对齐

参考效果

VS Code行号截图

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 15:00:24