textArea剩余字数统计插件

效果如:


js代码:

/**
 * textArea字数统计
 * 
 * Created on : 2015-6-26, 11:49:24
 * Author     : tom [email protected]
 */
var wordTool = {
    /**
     * 初始化
     * 
     * @param json json数组格式,如[{id:"news1", max:300}, {id:"news2", max:600}]
     */
    init: function (json) {
    	$.each(json, function(i, item) {
			 var id = item.id;
			 var max = item.max;
			 // 创建一个匿名div,将自身加入其中,获取textarea自身的html
			 myself_html = $('
').append($('#'+id).clone()).html(); html = '
'; html += myself_html; html += ''+max+'/'+max+''; html += '
'; $('#'+id).replaceWith(html); wordTool.statInputNum(id); }); wordTool.initCss(); }, /** * 剩余字数统计 * * @param id textArea的id */ statInputNum: function(id){ //先选出 textarea 和 统计字数 dom 节点 var div = $('.'+id); var textArea = div.find('#'+id); var wordWrap = div.find(".word"); var max = wordWrap.text(); textArea[0].setAttribute("maxlength", max); var curLength = textArea.val().length; wordWrap.text(max - curLength); textArea.on('input propertychange', function() { wordWrap.text(max - $(this).val().length); }); }, /** * 初始化样式 */ initCss: function(id){ $(".wordCount").css({"position": "relative"}); $(".wordCount .wordwrap").css({"position": "absolute","right": "6px","bottom": "6px"}); $(".wordCount .word").css({"color": "#990000", "padding": "0 4px"}); } }


你可能感兴趣的:(web)