jQuery实现Textarea字数统计

2015-11-27阅读(6169)评论(0)牵着狗狗看MM

苏州实时公交查询

HTML

<div class="item-textarea">
    <textarea></textarea>
    <i>500</i> characters left
</div>

CSS

.item-textarea{
    position: relative;
}
.item-textarea > textarea{
    width: 100%;
    height: 68px;
    padding: 10px;
    -webkit-border-radius: 4px;
    -moz-border-radius: 4px;
    border-radius: 4px;
    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);
    border: solid 1px #ddd;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    font-size: 0.14rem;
}
.item-textarea > span{
    display: block;
    position: absolute;
    right: 6px;
    bottom: 7px;
    color: #9a9a9a;
    font-size: 0.12rem;
}
.item-textarea > span > i{
    color: #55acef;
}

引入jQuery:

<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>

JS

<script>
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);
        });
    }
$(function () {
    $(".item-textarea").each(function () {
        var textArea = $(this).find("textarea"),
            word = $(this).find("i");
        statInputNum(textArea, word);
    });
});
</script>

Demo

赞(0)
转载请注明来源:Web前端(W3Cways.com) - Web前端学习之路 » jQuery实现Textarea字数统计
分享到: 更多 (0)