HTML/CSS/JS: How to make an illusion of a textarea with line numbers?

喜夏-厌秋 提交于 2019-12-05 10:28:48

I would start with two text-areas and synchronzation mechanism. Something like this,

    <script>
    window.sync = function(e){
            var textarea = document.getElementById("lines");
            var source   = document.getElementById("some_text_area");
            textarea.scrollTop = source.scrollTop;
        }

        window.populate = function populate(){
            if(populate.started){
                return;
            }

            populate.started = true;
            var textarea = document.getElementById("lines");
            var str = '';
            for(var i=0;i < 100;i++){
                str = str + (i +'\r\n');
            }
            textarea.value = str;
        }
    </script>

<div>
<textarea 
    style="width:40px;overflow:hidden;height:40px;" 
    readonly="true" 
    id="lines"
></textarea>
<textarea 
    style="width:500px;height:40px;" 
    id="some_text_area" 
    onclick="populate()"
    onscroll="sync();"
></textarea>
</div> 

Ofcourse populate() function (and the style declaration and event declaration) should be more robust and intelligent, , but, it just for showcase purpose.

I think your best bet would be to just have a regular textarea, and show a preview (like stack overflow) as they type along. Within that preview, you could easily add line numbers on each line and format the look via CSS.

Another simple method is to create a narrow, but tall background image and some left padding on the textarea. This has the minor caveat of having a fixed number of rows and font style, but it is the option with the least amount of code required.

Without images, that's a tough one.

Best bet: Place a second textarea with identical settings (font size, line height, padding...) but different styling (no background color, no borders) to the left of your original textarea. Make it read only, take it out of the tab rotation (tabindex=99999 might do the trick or simply disabling it), and put line numbers in it. This should work well and correctly as far as I can think, it should even survive things like the client resizing the font manually in their browser.

You could even use position: relative and a big padding-left: value in the original textarea to move the counter textarea into the original one.

Downside: The line counter won't follow vertical scrolling of the textarea. See the comments below.

You'd have to wrap the text area and capture the keystrokes looking for newline characters (Eg ENTER). Doing a quick Google search and you get http://www.dhtmlgoodies.com/forum/viewtopic.php?t=506

Personally I'd just have a regular textarea and a div down the left side that displays the numbers (possibly auto-adjusting as more carriage returns get added to it).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!