HTML / CSS / JS: How to create the illusion of a text field with line numbers?

I want to have a text box that displays line numbers on the left. Wrap must be set to "off" (for horizontal scrolling to be available). I want my page to be a single standalone .html file (there will be no graphics), so I would like to avoid any third-party frameworks.

Which direction should I go? How do you do this?

+5
source share
6 answers

I would start with two text areas and a synchronization mechanism. Something like that,

    <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() ( ) , .

+3

, (, ) . CSS.

+2

, . , .

+2

.

: ( , , ...), ( , ) , , (tabindex=99999 ) . , , , , .

position: relative padding-left: , .

: . . .

+1

div , (, , ).

0

All Articles