gpt4 book ai didi

javascript - 如何使用 javascript 在 html 文本框旁边制作自动行号?

转载 作者:搜寻专家 更新时间:2023-10-31 22:19:03 24 4
gpt4 key购买 nike

我看过像Github Gist这样的网站和 copy.sh左侧有带行号的文本框。

左边好像有一个section包含有行号的元素,每次新建一行的时候,左边会添加一个元素,有一个新的行号,当你删除一行的时候,最后一个行号被删除。

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

谢谢。

P.S 我宁愿避免使用 Jquery。

最佳答案

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

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);
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;
}
<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>

确保将这些都放在同一个目录中并保存为我列出的文件名。这个例子只有大约 30 行,但是你可以自己修改它来做你想做的事。此外,输入 HTML 标签也会搞砸它。您可以再次修改它以满足您的需要这只是一个简单的例子。

基本上您所做的是将文本从 textarea 复制到 div,然后根据 div 的高度计算 textarea 中的行数。

希望这对您有所帮助!

关于javascript - 如何使用 javascript 在 html 文本框旁边制作自动行号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36378371/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com