JQuery编写插件

/*
 * 用于统计input、textarea输入字数,
 * 使用:1.默认信息显示模式:$("#test).checkInputTextAreaLen();
 *      2.重写信息显示模式:$("#test).checkInputTextAreaLen({max:100,tip:'提示信息'});
 * */
(function($){
	$.fn.checkInputTextAreaLen = function(options){
		return this.each(function(){
			function countLength(value_para,max){
				var rt = ["",""];
		    	var value = ""||value_para;
				var curLen = 0;
				for (var i=0; i<value_para.length; i++) 
				{            
					if (value_para.charCodeAt(i)>127 || value_para.charCodeAt(i)==94) {     
		                curLen += 2;           
					}else {   
		                curLen ++;           
					}  
					if(curLen<=max){
						rt[0]+=value_para.charAt(i);
						rt[1]=curLen;
						break;
					}
				}		
				return rt;
			 };
			 function showWordCount(para,obj) {//显示字数 		     								        
	        	  var max = para.max;
	  	    	  var tip = para.tip;
	  	    	  var value =  obj.val();
		    	  var rt = countLength(value,max);
		    	  obj.val(rt[0]);
	              tip=tip.replace("{current}",max-rt[1]).replace("{max}",max);
	              obj.next("div").html(tip);
		     };
			 var defaluts ={ 
					max:100,//默认最大字节数
		            tip:"提示:限制输入{max}个字,还能输入{current}个字!" //提示信息
		     };
		     defaluts = $.extend(defaluts,options);
		     var _max = defaluts.max;
		     var _tip = defaluts.tip;
		     var divTip=$("<div class='textareaTip'></div>");
		     var _value = $(this).val();
		     var _length = countLength(_value);
		     var _tip=_tip.replace("{current}",_length).replace("{max}",_max);
	    	 divTip.html(_tip);
	         $(this).after(divTip);	
	         $(this).next("div").css('display','none'); 
	         $(this).keyup(function() {
	        	  //alert($(this).val());
	              showWordCount(defaluts,$(this));
	         });
	        $(this).focus(function(){ 	          	               
	        	showWordCount(defaluts,$(this));	                
	        	$(this).next("div").fadeIn('slow');
	         });
	          $(this).blur(function(){
	        	$(this).next("div").fadeOut('slow'); 
	         });
		});
	}
})(jQuery);


 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值