HTML--在textarea左侧添加行号

原文网址:HTML--在textarea左侧添加行号-CSDN博客

简介

本文介绍HTML在textarea文本框左侧添加行号的方法。

效果

代码

html 复制代码
<html xml:lang="cn" lang="cn">

<head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
    <meta name="keywords" content="anchor,fixed navigation hide anchor">
    <title>textarea测试</title>
    <style>
        .line-number-container {
            display: inline-block;
            padding: 2px 0 2px 1em;
            font-family: monospace;
            color: #999;
            position: absolute;
            left: 0;
            top: 0;
            bottom: 0;
            overflow-y: scroll;
            scrollbar-width: none; /* 禁止显示滚动条 */
        }

        .line-number-container::-webkit-scrollbar {
            width: 0; /* 禁止显示滚动条 */
        }

        .container textarea {
            width: 500px;
            height: 200px;
            padding-left: 2em;
            overflow: scroll;
        }
    </style>
</head>

<body>

<div class="container" style="position: relative;">
    <textarea wrap="off"></textarea>
    <div class="line-number-container"></div>
</div>

</body>

<script>
    createLineNumber('.container textarea', '.line-number-container')

    function createLineNumber(textAreaSelector, lineNumberSelector) {
        let textarea = document.querySelector(textAreaSelector);
        let lineNumber = document.querySelector(lineNumberSelector);
        updateLineNumbers();

        textarea.addEventListener("input", updateLineNumbers);
        textarea.addEventListener("scroll", syncScroll);
        lineNumber.addEventListener("scroll", syncContent);

        function updateLineNumbers() {
            let lines = textarea.value.split("\n");
            lineNumber.innerHTML = "";
            for (let i = 0; i < lines.length; i++) {
                let lineNum = document.createElement("div");
                lineNum.textContent = i + 1 + '';
                lineNumber.appendChild(lineNum);
            }

            let widthCount = String(lines.length).length;
            widthCount += 1;
            textarea.style.setProperty('padding-left', widthCount + 'em');
        }

        function syncScroll() {
            lineNumber.scrollTop = textarea.scrollTop;
        }

        function syncContent() {
            textarea.scrollTop = lineNumber.scrollTop;
        }
    }
</script>

</html>
相关推荐
ZhengEnCi5 天前
Q02-Vue-React-index.html完全指南
vue.js·react.js·html
牧艺5 天前
HTML-in-Canvas 深度解析:让 Canvas 真正「吃上」HTML 这碗饭
前端·html·canvas
爱勇宝6 天前
我给自己做了一个新标签页:不登录、不打扰、打开就能用
前端·html·浏览器
越努力越幸运666 天前
多模态代码调试实战:Gemini3.5 精准捕获 HTML 隐性语法
html
anOnion10 天前
构建无障碍组件之Menu Button pattern
前端·html·交互设计
米丘11 天前
微前端之 Web Components 完全指南
微服务·html
Metaphor69213 天前
使用 Python 将 PDF 转换为 HTML
python·pdf·html
a11177614 天前
“黑夜流星“个人引导页 网页html
java·前端·html
JieE21214 天前
手把手带你用纯 CSS 实现一个 3D 旋转魔方,这些前端基础你能打几分?
前端·css·html
YHL14 天前
🧊 CSS 3D 硬核解析:四个属性手写旋转立方体
前端·css·html