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>
相关推荐
GGGG寄了20 小时前
CSS——CSS引入方式+选择器类型
前端·css·html
qq_124987075320 小时前
基于html的书城阅读器系统的设计与实现(源码+论文+部署+安装)
前端·vue.js·spring boot·后端·mysql·信息可视化·html
a177988771221 小时前
小程序为什么 Upload 外层使用 display: flex 时会造成组件样式混乱
css·html·css3
咩咩不吃草21 小时前
【HTML】核心标签与【Python爬虫库】实战指南
css·爬虫·python·html
2601_949857431 天前
Flutter for OpenHarmony Web开发助手App实战:HTML参考
前端·flutter·html
fanruitian2 天前
div水平垂直居中
前端·javascript·html
Smart-Space2 天前
cpphtmlbuilder-c++灵活构造html
c++·html
tao3556673 天前
HTML-03-HTML 语义化标签
前端·html
pusheng20253 天前
普晟传感2026年新春年会总结与分析
前端·javascript·html
Emma_Maria3 天前
本地项目html和jquery,访问地址报跨域解决
前端·html·jquery