在可编辑的div上显示每行旁边的行号,可以通过以下步骤实现:
以下是一个示例的代码实现:
HTML:
<div class="editor-container">
<div class="line-number-container"></div>
<div contenteditable="true" class="editable-div"></div>
</div>
CSS:
.editor-container {
position: relative;
display: flex;
}
.line-number-container {
position: absolute;
left: 0;
top: 0;
width: 30px; /* 调整宽度以适应行号的长度 */
padding: 5px;
font-family: monospace; /* 使用等宽字体以保持对齐 */
background-color: #f0f0f0;
border-right: 1px solid #ccc;
}
.editable-div {
flex: 1;
padding: 5px;
font-family: monospace; /* 使用等宽字体以保持对齐 */
border: 1px solid #ccc;
overflow: auto;
}
JavaScript:
const editableDiv = document.querySelector('.editable-div');
const lineNumberContainer = document.querySelector('.line-number-container');
editableDiv.addEventListener('scroll', updateLineNumbers);
function updateLineNumbers() {
const scrollTop = editableDiv.scrollTop;
const lineHeight = parseInt(getComputedStyle(editableDiv).lineHeight);
const firstVisibleLine = Math.floor(scrollTop / lineHeight) + 1;
const lastVisibleLine = firstVisibleLine + Math.floor(editableDiv.clientHeight / lineHeight) - 1;
let lineNumbersHtml = '';
for (let i = firstVisibleLine; i <= lastVisibleLine; i++) {
lineNumbersHtml += `<div>${i}</div>`;
}
lineNumberContainer.innerHTML = lineNumbersHtml;
}
这样,当用户在可编辑的div中滚动时,行号容器会根据滚动位置动态更新显示的行号。你可以根据实际需求调整样式和布局。
领取专属 10元无门槛券
手把手带您无忧上云