textArea剩余字数统计插件

效果如:


js代码:

/**
 * textArea字数统计
 * 
 * Created on : 2015-6-26, 11:49:24
 * Author     : tom lyl010991@126.com
 */
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 = $('<div>').append($('#'+id).clone()).html();
			 html  = '<div class="wordCount '+id+'">';
			 html += myself_html;
			 html += '<span class="wordwrap"><var class="word">'+max+'</var>/'+max+'</span>';
			 html += '</div>';
			 $('#'+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"});
	 }
}


  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值