JS处理窗口Resize时文本换行与行号同步更新
使用 pre 元素包裹文本,配合 CSS white-space: pre-wrap 保留换行,通过 JavaScript 监听 resize 事件并重新计算行数,将行号注入到每行前。
CSS 布局与换行控制
确保容器使用 white-space: pre-wrap,这样文本在窗口缩放时会自动根据宽度换行,且保留原始空格和换行符。这是实现动态行号的基础,避免使用 div 导致换行行为不可控。
pre 标签默认不自动换行,必须显式设置样式。同时,需要为每一行分配唯一的标识或索引,以便后续插入行号。这里采用在每行前添加一个包含行号的 span 的方式,保持文本内容不变,仅增加视觉上的编号列。
Resize 事件下的行数重算
将完整程序放在 HTML 文件中,直接在浏览器打开即可运行。调整浏览器窗口大小,观察左侧行号是否随右侧文本换行同步更新。
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>JS Resize Text Line Numbers</title>
<style>
.container {
display: flex;
font-family: monospace;
border: 1px solid #ccc;
padding: 10px;
white-space: pre-wrap;
word-break: break-all;
}
.line-numbers {
width: 40px;
text-align: right;
color: #999;
user-select: none;
margin-right: 10px;
border-right: 1px solid #eee;
padding-right: 5px;
}
.text-content {
flex: 1;
overflow-x: auto;
}
</style>
</head>
<body>
<div class="container" id="editor">
<div class="line-numbers" id="lineNums"></div>
<div class="text-content" id="textContent">Line 1 of the text.
Line 2 is longer and might wrap when the window is narrow.
Line 3 is short.
This is a test to see if line numbers update correctly on resize.</div>
</div>
<script>
const editor = document.getElementById('editor');
const lineNums = document.getElementById('lineNums');
const textContent = document.getElementById('textContent');
function updateLineNumbers() {
// Get computed styles for accurate line-height calculation
const style = getComputedStyle(textContent);
const lineHeight = parseFloat(style.lineHeight);
// Calculate number of lines based on scrollHeight and lineHeight
// scrollHeight includes padding, so we subtract container padding if necessary
// But for simple pre-wrap, scrollHeight / lineHeight is usually close enough
// A more robust way for pre-wrap is to measure a clone or use getClientRects
// However, for this demo, we will use a hidden measurement div approach
// Create a temporary element to measure exact rendered height
const tempDiv = document.createElement('div');
tempDiv.style.width = textContent.clientWidth + 'px';
tempDiv.style.whiteSpace = 'pre-wrap';
tempDiv.style.wordBreak = 'break-all';
tempDiv.style.fontFamily = style.fontFamily;
tempDiv.style.fontSize = style.fontSize;
tempDiv.style.lineHeight = style.lineHeight;
tempDiv.style.padding = style.padding;
tempDiv.textContent = textContent.textContent;
document.body.appendChild(tempDiv);
const actualHeight = tempDiv.scrollHeight;
document.body.removeChild(tempDiv);
let lines = Math.ceil(actualHeight / lineHeight);
// Ensure at least one line if there's content
if (lines === 0 && textContent.textContent.length > 0) {
lines = 1;
}
// Generate line numbers
let html = '';
for (let i = 1; i <= lines; i++) {
html += i + '\n';
}
lineNums.textContent = html;
}
// Debounce function
function debounce(func, wait) {
let timeout;
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
// Initial call
updateLineNumbers();
// Listen for resize
window.addEventListener('resize', debounce(updateLineNumbers, 100));
</script>
</body>
</html>
程序输出为带行号的文本区域。当浏览器窗口宽度变化时,文本发生换行,行数改变,左侧行号列会重新计算并显示正确的数字序列。如果文本为空,行号为 0 或不显示(取决于具体实现,此处若内容为空则 lines=0,html 为空)。调试时,检查控制台是否有报错,并确保 debounce 函数正常工作以避免频繁计算。
核心逻辑在于获取元素的实际行数。由于 pre 的换行由浏览器渲染引擎决定,我们可以通过计算总高度除以单行高度来估算,或者更可靠地,利用 getComputedStyle 获取 line-height,结合 scrollHeight 进行计算。但最稳健的方法是解析文本内容,因为 pre 中的换行符 \n 是明确的,但在自动换行场景下,物理行数不等于逻辑换行符数量。因此,我们创建一个隐藏的测量元素,复制其样式和内容,通过比较其 offsetHeight 和 line-height 来获得准确的物理行数。
行号注入与性能优化
直接回答如何高效地将行号应用到每一行而不引起重排抖动。关键在于批量操作 DOM 或使用虚拟列表,但对于短文本,直接重建行号列即可。
为了避免每次 resize 都触发多次重绘,应使用 requestAnimationFrame 或防抖函数限制更新频率。在计算出行数后,生成对应的行号 HTML 字符串,一次性替换行号容器的内容。注意处理空行和末尾换行的情况,确保行号从 1 开始连续递增,且与可视区域的行数严格对应。
JS解析带命名空间(xmlns)的XML节点获取失败怎么办
2026-12-05
JS怎么实现输入框只读但保留光标和正常样式
2026-12-05
link标签能直接运行JavaScript吗?浏览器兼容性说明
2026-12-05
JS怎么在移动端Touch事件中获取等效鼠标坐标
2026-12-05





