且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

统计Textarea的输入字符数

更新时间:2022-09-21 22:56:06

HTML代码:

1
2
3
4
<div class="item-textarea">
    <textarea></textarea>
    <span>还可以输入<i>500</i>个文字</span>
</div>


CSS代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
.item-textarea{
    positionrelative;
}
.item-textarea textarea{
    width100%;
    height100px;
    padding10px;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
    border-radius: 5px;
    background#fff;
    -webkit-box-shadow: inset 0 1px 2px rgba(0,0,0,.3);
    -moz-box-shadow: inset 0 1px 2px rgba(0,0,0,.3);
    box-shadow: inset 0 1px 2px rgba(0,0,0,.3);
    border1px solid #ddd;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    font-size0.14rem;
}
.item-textarea span{
    displayblock;
    positionabsolute;
    right6px;
    bottom7px;
    color#9a9a9a;
    font-size0.12rem;
}
.item-textarea span i{
    color#55acef;
}


简单看下当前的页面效果:

统计Textarea的输入字符数

为了方便,首先引入jQuery文件,这里用到一个匿名的自调函数

1
2
3
4
5
6
7
8
9
10
11
12
13
(function( ){
    var textArea = $('textarea');
    var numItem = $('i');
    var max = numItem.text(); //i标签中的内容,也就是最多可以显示的字符数
    var curLength = textArea.val().length; //当前的字符数
 
    textArea.attr('maxlength',max); //设置最大字符数,如果去掉的话,i标签内会出现负数
    numItem.text(max - curLength); //实时更新i标签中的数量
    textArea.on('input propertychange'function () {
        //$(this) ---> 指代textarea
        numItem.text(max - $(this).val().length);
    });
})()

本文转自   frwupeng517   51CTO博客,原文链接:http://blog.51cto.com/dapengtalk/1867095