文本框 textarea 动态显示行数(简单文本编辑器)

工作需求做一个文本编辑器简单的。

右边输入文字,左边会显示相应的代码行。清空也会变为1.

废话不多说上代码,自己理解。

<style type="text/css">
*{margin: 0; padding: 0;}
html,body{height: 100%; margin: 0; padding: 0;font: 12px/1.5 tahoma, arial, 'hiragino sans gb', 'microsoft yahei', sans-serif;-webkit-font-smoothing: antialiased;}
#mian{ width:640px; height:100%;}
#leftBox{background:#ecf0f5;width:35px; height:100%; text-align:left; float: left;}
#test{border:1px solid #eaeaea; outline:none; width:600px; height:100%; resize: none; background: rgb(250,250,250); line-height: 24px;font-size: 14px;float: left; padding:10px 8px;  color: black; font-family: inherit; box-sizing: border-box;}
#leftNum{ height:100%; width: 100%; resize: none;outline:none; overflow-y: hidden; overflow-x: hidden; border: 0; background: rgb(247,247,247); color: #999;line-height: 24px;font-size: 14px; padding:10px 4px; text-align: right; font-weight: bold; box-sizing: border-box;}
</style>
 1 <div id="mian">
 2     <div id="leftBox"><textarea wrap="off" cols="2" id="leftNum" disabled></textarea></div>
 3     <textarea id="test" name="content" onkeydown="keyUp()" onscroll="getId('leftNum').scrollTop = this.scrollTop;">
 4     </textarea>
 5 </div>
 6 <script type="text/javascript">
 7 var num = "";
 8 var btn = getId('btn');
 9 var test = getId('test');
10 function getId(obj) {
11     return document.getElementById(obj);
12 }
13 function keyUp(){
14     var str = test.value; 
15     str = str.replace(/\r/gi,"");
16     str = str.split("\n");
17     n = str.length;
18     line(n);
19 }
20 function line(n){
21     var lineobj = getId("leftNum");
22     for(var i = 1;i <= n;i ++){
23        if(document.all){
24         num += i + "\r\n";//判断浏览器是否是IE  
25        }else{
26         num += i + "\n";
27        }
28     }
29     lineobj.value = num;
30     num = "";
31 }
32 
33 (function() {
34     keyUp();
35 })();
36 </script>

 

posted @ 2016-09-02 16:21  to_Matthew  阅读(5871)  评论(0编辑  收藏  举报