HTML / CSS / JS:如何用行号制作textarea的错觉? [英] HTML/CSS/JS: How to make an illusion of a textarea with line numbers?

查看:140
本文介绍了HTML / CSS / JS:如何用行号制作textarea的错觉?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要在左边显示行号的textarea。包裹应设置为关闭(以便水平滚动可用)。我希望将我的页面作为一个自包含的.html文件(将不会有图形),因此我想避免使用任何第三方框架。

I want to have a textarea which displays line numbers on the left. Wrap should be set to "off" (so that horizontal scrolling is available). I want to have my page as a single self-contained .html file (there will be no graphics), so I'd like to avoid any 3rd party frameworks.

我应该走哪条路?你会如何做到这一点?

Which way should I go? How would you do this?

推荐答案

我将从两个文本区域和同步机制开始。
就像这样,

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> 



populate()函数样式声明和事件声明)应该更加健壮和聪明,但是,它只是为了展示目的。

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

这篇关于HTML / CSS / JS:如何用行号制作textarea的错觉?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆