获取textarea的字符数,包括换行符 [英] Get the character count of a textarea including newlines

查看:254
本文介绍了获取textarea的字符数,包括换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Chrome中测试了此代码,似乎存在涉及换行符的错误。在实际使用所有字符之前,我达到了最大长度。

I tested this code in Chrome and there seems to be a bug involving the newlines. I am reaching the maxlength before I actually use all the characters.

var ta = document.getElementById('myText');

document.getElementById('max').innerHTML = ta.maxLength;

setInterval(function() {
    document.getElementById('count').innerHTML = ta.value.length;
}, 250);

<textarea id="myText" maxlength="200" style="width:70%;height:130px">
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum has been the industry's standard dummy text ever since the 1500s
Type more words here...
</textarea>

<div>
    Char Count <span id="count">0</span>/<span id="max">0</span>
</div>

如何准确获取textarea的字数呢?

How can I accurately get the char count of a textarea?

更新1
我报告 bug 到Chromium团队,它似乎是低优先级。

Update 1 I reported the bug to the Chromium team and it seems to be low priority.

更新2
那个bug是合并到另一个错误

更新3
该错误似乎已修复!

Update 3 The bug appears to be fixed!

推荐答案

似乎是一个WebKit错误(考虑归档)与将CR / LF对视为两个字符有关而不是一个。因为它通常是非关键性的,例如,允许197个字符而不是200个字符,可以忽略它。

Seems to be a WebKit bug (consider filing it) related to treating CR/LF pair as two characters instead of one. Since it's usually noncritical if, say, 197 characters are allowed instead of 200, it's fine to ignore this.

但如果你愿意,你可以尝试不断保存插入位置,将所有 \ r \ n 替换为 \ n ,并在用户输入时恢复textarea中的插入位置。

But if you want, you can try to continuously save caret position, replace all \r\n to \n, and restore caret position in textarea while user is typing.

这篇关于获取textarea的字符数,包括换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆