首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如果在Textarea中有空行,则为2个新行字符

如果在Textarea中有空行,则为2个新行字符
EN

Stack Overflow用户
提问于 2022-11-23 19:27:46
回答 1查看 45关注 0票数 1

我试图获取文本区域为行计数器(对于文本编辑器)所拥有的行数,但如果文本区域中有emtpy行,则添加两行。这是输出:

代码语言:javascript
复制
["// Hello World!","","","The line above was empty","","","Same here!","The line on the bottom of this one is empty!","",""]

我的代码:

代码语言:javascript
复制
function getLines() {
  var textValue = document.querySelector('#editor').value;
  var lines = textValue.split("\n");
  console.log(lines);
}

应某人的请求,以下是HTML:

代码语言:javascript
复制
    <div id="visible" contenteditable="true"
    onkeyup="updateLineCount()">// Hello World!</div>
    <textarea id="code-editor">

基本上,我计划添加语法高亮显示,因此div是内容可编辑的,JS将div中的内容发送到textarea,只为了计算代码行。以下是执行此操作的JS:

代码语言:javascript
复制
    textarea.value = document.querySelector("#code-editor").innerText;
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-11-24 22:32:42

您所遇到的问题与提取可内容div的innerText值并将其放入<textarea>有关。这就是额外的换行符\n的来源。

除非需要使用<textarea>,否则我将直接从可内容的div获取行计数。这里唯一奇怪的地方是在innerText的末尾添加了一个额外的换行符\n,但是这可以使用.split(0, -1)删除。

代码语言:javascript
复制
const updateLineCount = () => {
  document.querySelector(".lines").innerHTML = [...Array(document.querySelector("#code-editor").innerText.slice(0, -1).split("\n").length).keys()].map(v => v+1).join("<br>")
}
document.querySelector("#code-editor").addEventListener("keyup", updateLineCount)
代码语言:javascript
复制
.code {
  padding: .2em .4em;
  border: 1px solid #CCC;
  box-sizing: border-box;
  display: inline-block;
}
.lines {
  color: #555;
  font-family: monospace;
  width: 2em;
  vertical-align: top;
  border-right: 1px solid #CCC;
  display: inline-block;
}
#code-editor {
  font-family: monospace;
  width: 40em;
  vertical-align: top;
  display: inline-block;
}
#code-editor:focus { outline: none; }
代码语言:javascript
复制
<div class="code">
  <div class="lines">1</div>
  <div id="code-editor" contenteditable="true">// Hello World!</div>
</div>

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74552066

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档