页面加载时自动显示textarea行号的实现问题
页面加载时文本域行号不显示的修复方案
问题现状
- 已实现:通过
keydown/keyup事件,按键编辑文本时能正确生成对应行号 - 未解决:页面加载完成后,无法识别文本域的初始行数(比如初始有3行文本,仅显示1行号),需要实现页面加载自动生成正确行号,且不冲突现有按键功能
用户曾尝试一段无效代码(意图实现加载时触发更新,但逻辑错误):
//VIEW DIRECTLY (WITHOUT PRESSING A BUTTON) const start2 = textarea.selectionStart; const end2 = textarea.selectionEnd; textarea.value = textarea.value.substring(0, start2) + "\t" + textarea.value.substring(end2);
修复方案
把行号更新逻辑封装成独立函数,在页面加载和文本内容变化时统一调用:
- 封装
updateLineNumbers函数:根据文本域内容的换行符分割行数,生成对应数量的<span>元素插入行号栏 - 页面加载完成后立即调用该函数,初始化行号
- 保留原有Tab键插入逻辑,在
keyup事件中调用同一函数更新行号
修改后的完整代码
HTML
<div class="code-area editor"> <div class="numbers"> <span></span> </div> <textarea id="htmlCode" placeholder="HTML" placeholder="PROVA" wrap="off">Test 1 Test 2 Test 3</textarea> </div>
CSS
.editor { display: inline-grid; grid-template-columns: 3em auto; gap: 10px; line-height: 21px; border-radius: 2px; overflow-y: auto; width: 100%; } .editor>* { padding-top: 10px; padding-bottom: 10px; } .numbers { text-align: right; background: #333; padding-right: 5px; height: 150px; } .numbers span { counter-increment: linenumber; } .numbers span::before { content: counter(linenumber); display: block; color: #888; } textarea { line-height: 21px; border: 0; background: transparent; color: #fff; min-width: 500px; outline: none; resize: none; padding-right: 10px; } textarea::placeholder{ color: red; } textarea{ background-color: black; color: green; }
JavaScript
const textarea = document.querySelector("textarea"); const numbers = document.querySelector(".numbers"); // 封装行号更新函数 function updateLineNumbers() { const lineCount = textarea.value.split("\n").length; numbers.innerHTML = Array(lineCount).fill("<span></span>").join(""); } // 页面加载时初始化行号 updateLineNumbers(); // 按键编辑时更新行号 textarea.addEventListener("keyup", updateLineNumbers); // Tab键插入制表符逻辑 textarea.addEventListener("keydown", (event) => { if (event.key === "Tab") { const start = textarea.selectionStart; const end = textarea.selectionEnd; textarea.value = textarea.value.substring(0, start) + "\t" + textarea.value.substring(end); event.preventDefault(); } });
内容的提问来源于stack exchange,提问作者Nodigap
相关产品推荐
相关产品推荐

