如何使用javascript在html文本框旁边创建自动行号?

the*_*row 3 html javascript textbox line-numbers

我见过像Github Gistcopy.sh这样的网站,左边是行号文本框.

似乎左边有一个包含行号的元素,每次创建一个新行时,左边都会添加一个元素,新行号,当你删除一行时,最后一行号是删除.

我查看了javascript,但是我无法理解.我如何实现这样的部分(带行号的文本框)?

谢谢.

PS我宁愿避免Jquery.

小智 5

我在这里给你一个简单的例子......

var divCopy = document.getElementById('copyText'),
nmbrBox = document.getElementById('numbers'),
txtBox = document.getElementById('textBox'),
lineHeight = 20;

//Bind events to elements
function addEvents() {
  "use strict";
  txtBox.addEventListener("keyup", copyText, false);
  txtBox.addEventListener("keyup", addLines, false);
}

/*
  This function copies the text from the textarea to a div 
  so we can check the height and then get the number of lines 
  from that information
*/
function copyText() {
  "use strict";

  //variable to hold and manipulate the value of our textarea
  var txtBoxVal = txtBox.value;

  //regular expression to replace new lines with line breaks
  txtBoxVal = txtBoxVal.replace(/(?:\r\n|\r|\n)/g, '<br />');

  //copies the text from the textarea to the #copyText div
  divCopy.innerHTML = txtBoxVal;
}

function addLines() {
  "use strict";
  var lines = divCopy.offsetHeight / lineHeight, x = 1, holder = '';
  for (x = 1; x <= lines; x = x + 1) {
    holder += '<div class="row">' + x + '.</div>';
  }
  if (lines === 0) {
    holder = '<div class="row">1.</div>';
  }
  nmbrBox.innerHTML = holder;
}

window.addEventListener("load", addEvents, false);
Run Code Online (Sandbox Code Playgroud)
html, body{
  font-size: 10px;
  height: 100%;
}

textarea{
  background: #f3f3f3;
  color: #111;
  font-family: sans-serif;
  font-size: 1.8em;
  line-height: 20px;
  min-height: 600px;
  min-width: 800px;
  resize: none;
  overflow: hidden;
  position: absolute;
  left: 56px;
}

textarea:focus{
  outline: 0;
}

textarea, .rows{
  display: inline-block;
}

.rows{
  background: #e3e3e3;
  box-sizing: border-box;
  color: #999;
  font-family: monospace;
  font-size: 1.8em;
  height: 100%;
  line-height: 20px;
  max-height: 600px;
  overflow: hidden;
  padding: 0.16em 0em;
  text-align: right;
  width: 48px;
  vertical-align: top;
}
    
#copyText{
  display:inline-block;
  font-family: sans-serif;
  font-size: 1.8em;
  line-height: 20px;
  visibility: hidden;
}
Run Code Online (Sandbox Code Playgroud)
<div class="container">
  <div class="rows" id="numbers">
    <div class="row">1.</div>
  </div>
  <textarea rows="30" id="textBox"></textarea>
  <div id="copyText"></div>
</div>
<script src="script.js" type="text/javascript"></script>
Run Code Online (Sandbox Code Playgroud)

确保将这些全部放在同一目录中并保存为我列出的文件名.此示例仅跨越大约30行,但您可以自己修改它以按照您的意愿执行.此外,输入HTML标签也会搞砸.您可以再次修改它以满足您的需求这只是一个简单的例子.

基本上你正在做的是将文本从textarea复制到div,然后根据div的高度计算textarea中的行数.

希望这可以帮助!