问题
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>
How can I accurately get the char count of a textarea?
Update 1 I reported the bug to the Chromium team and it seems to be low priority.
Update 2 That bug was merged into another bug.
Update 3 The bug appears to be fixed!
回答1:
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.
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.
来源:https://stackoverflow.com/questions/12924591/get-the-character-count-of-a-textarea-including-newlines