JavaScript textarea 获取行数(带换行符)
JavaScript textarea get numbers of lines (with linebreaks)
我有一个文本区域,我想知道有多少行。现在我搜索了,但我只看到这个解决方案:
mytextarea.value.split("\n").length
好吧,那行得通,但这不是我想要的。
例如我的textarea是这样的:
当我输入这个时:
123456789abcdefghijkl
sasasasakasasask;as
当我使用 split("\n").value 时,我得到 2,这是正确的,但如果我将其放入:
123456789abcdefghijklsasasasasasasasasas
我得到的结果 1 不正确:
结果应该是 2,因为有 2 行,但是换行符不是用 \n
创建的。
任何人都知道如何计算行数,包括没有 \n
的换行符?
在每行的末尾,按 Enter 键。当您按下 Enter 时,将 \n 插入行。
<html>
<head>
</head>
<body>
<textarea id="myTxt"></textarea>
<button id ="btn" onclick="myLine()">Try</button>
<p id="x"></p>
<script>
function myLine() {
var txt = document.getElementById("myTxt");
var x = document.getElementById("x");
x.innerHTML =txt.value.split("\n").length;
}
</script>
</body>
</html>
知道了!
static lineCaculator() {
let dummy = document.createElement('div');
dummy.style.font = AutoTextareaResizer.computedStyle.call(this, 'font');
dummy.style.width = AutoTextareaResizer.computedStyle.call(this, 'width');
dummy.style.wordWrap = 'break-word';
dummy.innerHTML = this.value;
document.body.appendChild(dummy);
let lines = parseInt(AutoTextareaResizer.computedStyle.call(dummy, 'height')) / this.realLineHeight;
document.body.removeChild(dummy);
return Math.max(1, lines);
}
我有一个文本区域,我想知道有多少行。现在我搜索了,但我只看到这个解决方案:
mytextarea.value.split("\n").length
好吧,那行得通,但这不是我想要的。
例如我的textarea是这样的:
当我输入这个时:
123456789abcdefghijkl
sasasasakasasask;as
当我使用 split("\n").value 时,我得到 2,这是正确的,但如果我将其放入:
123456789abcdefghijklsasasasasasasasasas
我得到的结果 1 不正确:
结果应该是 2,因为有 2 行,但是换行符不是用 \n
创建的。
任何人都知道如何计算行数,包括没有 \n
的换行符?
在每行的末尾,按 Enter 键。当您按下 Enter 时,将 \n 插入行。
<html>
<head>
</head>
<body>
<textarea id="myTxt"></textarea>
<button id ="btn" onclick="myLine()">Try</button>
<p id="x"></p>
<script>
function myLine() {
var txt = document.getElementById("myTxt");
var x = document.getElementById("x");
x.innerHTML =txt.value.split("\n").length;
}
</script>
</body>
</html>
知道了!
static lineCaculator() {
let dummy = document.createElement('div');
dummy.style.font = AutoTextareaResizer.computedStyle.call(this, 'font');
dummy.style.width = AutoTextareaResizer.computedStyle.call(this, 'width');
dummy.style.wordWrap = 'break-word';
dummy.innerHTML = this.value;
document.body.appendChild(dummy);
let lines = parseInt(AutoTextareaResizer.computedStyle.call(dummy, 'height')) / this.realLineHeight;
document.body.removeChild(dummy);
return Math.max(1, lines);
}