|
[其他]
分享一个简单的统计并限制textarea字数的小方法
[复制链接]
本帖最后由 JoviChin 于 2017-7-27 10:38 编辑
下面是效果
我用的是AUI前端框架,你也可以自定义自己的样式
CSS
- .wordCount textarea {
- width: 100%;
- height: 100px;
- }
- .wordCount .wordwrap {
- position: absolute;
- right: 0;
- bottom: -1rem;
- color: #BBBBBB;
- font-size:0.6rem;
- }
- .wordCount .word {
- padding: 0 0.2rem;
- }
复制代码
HTML
- <li class="aui-list-item-noborder aui-margin-b-15 wordCount" id="wordCount">
- <textarea name="desc" id="desc" placeholder="描述你的问题"></textarea>
- <span class="wordwrap"><var class="word">200</var>/200</span>
- </li>
复制代码
JS
- $(function() {
- //先选出 textarea 和 统计字数 dom 节点
- var wordCount = $("#wordCount"),
- textArea = wordCount.find("textarea"),
- word = wordCount.find(".word");
- //调用
- statInputNum(textArea, word);
- });
- /*
- * 剩余字数统计
- * 注意 最大字数只需要在放数字的节点那里直接写好即可 如:<var class="word">200</var>
- */
- function statInputNum(textArea, numItem) {
- var max = numItem.text(),
- curLength;
- textArea[0].setAttribute("maxlength", max);
- curLength = textArea.val().length;
- numItem.text(max - curLength);
- textArea.on('input propertychange', function() {
- numItem.text(max - $(this).val().length);
- });
- }
复制代码
以上,完毕。
|
|