角文本区计数器换行符短信 [英] Angular Text Area Counter Line Breaks SMS

查看:212
本文介绍了角文本区计数器换行符短信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做一个模仿手机短信字符计数器。我知道了计数字符,空格和换行,但我的柜台不同。换行,就在计数message.length就减1,但不会超过一个的最大长度。我想有更多的空间缩进时添加的,但不知道如何让message.length设置相同最大长度。

I'm trying to make a character counter that mimics a phone for SMS. I've got it counting characters, spaces, and line breaks, however my counters differ. With line breaks, it decrements by 1 in the count for message.length, but does for more than one in the maxlength. I'm thinking that more spaces are added in when indented, but not sure how to get the message.length set the same as maxlength.

<div class="col-md-6">
    <textarea rows="4" class="form-control" data-ng-model="message" maxlength="160" data-ng-trim="false"></textarea>
    <h6 id="characters">
        <span>Characters left: {{160 - message.length}}</span>
    </h6>
</div>

http://jsfiddle.net/9DbYY/303/

须─这个答案实际上并没有对这项工作(它计数空格和换行符为1):
angularjs文本区域字符计数器

Also- this answer doesn't actually work for this (it counts spaces and line breaks as 1): angularjs text area character counter

推荐答案

所以,你需要算作两个字符是实际的换行符(换行符手动输入的用户,而不是所造成的虚换行符唯一文字长于textarea的宽度允许的话)?

So the only thing you need to count as two characters are actual line breaks (line breaks entered manually by the user, not "virtual" line breaks caused by the text being longer than the textarea width allows)?

那么我建议这样的:

<span>{{160 - message.length - (message.length ? message.split("\n").length-1 : 0)}} left</span>

http://jsfiddle.net/9DbYY/306/

message.split(\\ n)。长度部分计算你得到你换行符拆分消息后的数量。不换行的消息让你一部分,一个换行符的消息让你两部分,等 - 因此 1 。和分裂一个空字符串也让你一个结果,为此检查,如果消息的长度在所有第一。

message.split("\n").length counts the number of parts you get after you split the message at line breaks. A message without a line break gets you one "part", a message with one line break gets you two parts, etc. – hence the -1. And splitting an empty string still gets you one result, therefor the check if the message has a length at all first.

根据定义,浏览器必须以一个textarea的值\\ n返回换行符 - 那些由 message.length算作一个字符了,所以我们只是减去的\\ n 字符数一遍,从而计算每个 \\ n 两个的结果中的字符。 (我想他们在短信的长度计为两个,因为这实际上可能使用 \\ r \\ n 换行。)

By definition, a browser has to return line breaks in a textarea’s value as \n – those are counted as one character by message.length already, so we just subtract the number of \n characters again, thereby counting each \n as two characters in the result. (I suppose they are counted as two in an SMS text message length, because that might actually be using \r\n for line breaks.)

这篇关于角文本区计数器换行符短信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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