基于jquery的輸入字數統計小控件
最近項目中加入社區話題功能,發布話題時多處用到對于文本框輸入字數進行統計的功能,因此寫了一個小控件供大家使用。
主要實現功能:
1、統計當前文本域、輸入框已輸入字符數。
2、計算剩余可以輸入字符數。
3、當輸入字符達到上限時切換提示樣式,給予提示。
4、支持傳入自定義事件在輸入字數達到某個數值時執行。
5、區分中英文字符統計。
效果圖如下:

/** * author:gew * * 本方法用于實時統計輸入框已輸入的字數 * * 調用方法示例: * $("#xxx").checkInputNum({ * "maxNum":1000, 輸入字符上限 * "nowNumTip":$("span .nownum"), 指定顯示已輸入多少字符的dom元素 * "restNumTip":$("span .restnum"), 指定顯示可輸入多少字符的dom元素 * "restTipClass":"red", 字數已經達到上線時改變restNumTip的樣式 * "checkType":"En" 指定統計的單位,CN:中文字符 EN:英文字符 * }); * */ if (!!window.jQuery) { (function($) { $.fn.extend({checkInputNum:function(options) { var option = { maxNum : 1000, //用戶可輸入最大字符數 triggerNum:1000, //當輸入數量達到某個值時觸發一個事件 triggerFunc:null, //觸發執行的事件 nowNumTip:null, //用于提示當前已輸入字數的dom對象 restNumTip:null, //用于提示還可以輸入字數的dom對象 restTipClass : null, //已輸入字數等于最大輸入字數時改變對象的class checkType:"CN" //字數統計類型 CN:中文,EN:英文 }; if (typeof options === "object") { $.extend(option, options); } if(isNaN(option.maxNum)){ return false; } var _this = this; var _result = true; var _nowNum = 0; var _restNum = 0; var _nowStrLen = 0; var _maxLength = option.checkType == "CN"? option.maxNum*2:option.maxNum; var _nowStr = ""; $(_this).bind("keyup change",function(){ _nowStr = checkLen(_this.val(),_maxLength); _nowNum = getNum(_nowStrLen, option.checkType); _restNum = getNum(_maxLength-_nowStrLen, option.checkType); if(_restNum<=option.triggerNum && typeof(option.triggerFunc)=="function"){ option.triggerFunc(); } //判斷已輸入字符數是否超出最大值 _result = _nowNum >= option.maxNum; if(!_result){//未超出界限 if(option.nowNumTip){ $(option.nowNumTip).html(_nowNum); } if(option.restNumTip){ $(option.restNumTip).html(_restNum); if(option.restTipClass&&typeof option.restTipClass =="string"){ $(option.restNumTip).removeClass(option.restTipClass); } } }else{//超出界限 $(_this).val(_nowStr); if(option.nowNumTip){ $(option.nowNumTip).html(_nowNum); } if(option.restNumTip){ $(option.restNumTip).html(_restNum); if(option.restTipClass&&typeof option.restTipClass =="string"){ $(option.restNumTip).addClass(option.restTipClass); } } } }); if($(_this).val()!==""){ $(_this).trigger("change"); } //校驗字符串長度是否合法,若不合法則截取字符串 function checkLen(str,len){ var num = getBytes(str); if(parseInt(num)>=len){ _nowStrLen = len; return subStr_func(str,len); }else{ _nowStrLen = num; return str; } } //根據統計類型判斷獲取字符數 function getNum(num,chType){ if(isNaN(num)){ return 0; }else{ if(chType=="CN"){ return Math.ceil(num/2); }else{ return num; } } } //獲取字符串字節數 function getBytes(str) { var byteLen = 0, len = str.length; if (str) { for ( var i = 0; i < len; i++) { if (str.charCodeAt(i) > 255) { byteLen += 2; } else { byteLen++; } } return byteLen; } else { return 0; } } //截取字符串使其長度不大于指定長度 function subStr_func(str, len) { if (!str || !len) { return ""; } var a = 0; var i = 0; var temp = ''; for (i = 0; i < str.length; i++) { if (str.charCodeAt(i) > 255) { a += 2; } else { a++; } if (a > len) { return temp; } temp += str.charAt(i); } } }}); })(jQuery); }
2012-05-14

浙公網安備 33010602011771號