gpt4 book ai didi

javascript - 在提交表单之前阅读文本区域中的换行符?

转载 作者:太空狗 更新时间:2023-10-29 15:17:22 24 4
gpt4 key购买 nike

我有一个带有属性 wrap="hard"的文本区域,这意味着我应该能够在提交到服务器后获得换行符(新行)——这可行。但我想做的是获取在提交之前创建的新行。

为什么?因为我想计算当前可见的行数。现在我不是在谈论回车行。我说的是通过限制文本区域的宽度(或设置 cols 属性)创建的行。

我有这个文本框:

<textarea id="myarea" name="myarea" cols="35" rows="10" wrap="hard">
Some example text here. Hello my name is something I should be able to blabla.
</textarea>

在浏览器中输出:
这里有一些示例文本。你好,我的名字是
我应该能够 blabla 的东西。

行数 = 2

我试过了:
$('#myarea').html().split("\n").length
$('#myarea').val().split("
").length
$('#myarea').val().split("\r").length
还有一些组合...

但没有一个有效。如果不编写计算每个字符然后创建换行符的脚本,我什至可能会问什么?我希望这会“自动”发生......

如果这不可能,为什么服务器可以解释(找到)新行,而我不能?

谢谢!

最佳答案

似乎没有内置工具来获取此值。但是我们可以计算一下。假设 textarea 中的 line-height 是一个已知值(你可以在 css 中显式定义它)。所以计算行数的代码是这样的:

    var area = $('#myarea').get(0);

//save the initial height of textarea
var initialHeight = area.style.height;

//set the height to 0 so scrollHeight will always return dynamic height
area.style.height = '0px';

//here we assume that the line-height equals to 15
var numberOfRows = Math.floor(area.scrollHeight / 15);

//restore textarea height
area.style.height = initialHeight;

console.log(numberOfRows);

工作示例 http://jsfiddle.net/J5UpF/

更新

刚刚用我的代码找出了 Chrome 中的错误。我没有考虑出现在 textarea 右侧的滚动条。这有时会导致错误的行数计算。然而,它在 Firefox 中就像一个魅力。要解决此问题,我们必须计算滚动条宽度的差异并相应地调整文本区域的宽度:

var area = $('#myarea').get(0);
var $area = $('#myarea');

//save the initial height of textarea
var initialHeight = area.style.height;

var scrollbarWidthInitial = area.offsetWidth - area.clientWidth;

//set the height to 0 so scrollHeight will always return dynamic height
area.style.height = '0px';

var scrollbarWidth = area.offsetWidth - area.clientWidth;
var scrollbarWidthDiff = scrollbarWidth - scrollbarWidthInitial;
$area.width($area.width() + scrollbarWidthDiff);

//here we assume that the line-height equals to 15
var numberOfRows = Math.floor(area.scrollHeight / 15);

//restore textarea height
area.style.height = initialHeight;
$area.width($area.width() - scrollbarWidthDiff);

console.log(numberOfRows);

更新示例 http://jsfiddle.net/J5UpF/3/

更新 2

在 Chrome 中发现了一个新的令人敬畏的错误!当使用 placeholder 属性时,Chrome 会计算占位符文本的行数。解决方法很简单:当您在 textarea 中输入一些数据时,只需备份占位符属性,并在数据被清除时恢复它。

更新示例 http://jsfiddle.net/J5UpF/4/

关于javascript - 在提交表单之前阅读文本区域中的换行符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16759756/

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