本文實例講述了jQuery擴展實現(xiàn)text提示還能輸入多少字節(jié)的方法。分享給大家供大家參考,具體如下:
1.添加jQuery自定義擴展
$(function($){ // tipWrap: 提示消息的容器 // maxNumber: 最大輸入字符 $.fn.artTxtCount = function(tipWrap, maxNumber){ var countClass = 'js_txtCount', // 定義內(nèi)部容器的CSS類名 fullClass = 'js_txtFull', // 定義超出字符的CSS類名 disabledClass = 'disabled'; // 定義不可用提交按鈕CSS類名 // 統(tǒng)計字數(shù) var count = function(){ var val = lenFor($.trim($(this).val())); if (val <= maxNumber){ tipWrap.html('<span class="' + countClass + '">/u8FD8/u80FD/u8F93/u5165 <strong>' + (maxNumber - val) + '</strong> /u4E2A/u5B57/u8282</span>'); }else{ tipWrap.html('<span class="' + countClass + ' ' + fullClass + '">/u5DF2/u7ECF/u8D85/u51FA <strong>' + (val - maxNumber) + '</strong> /u4E2A/u5B57/u8282</span>'); }; }; $(this).bind('keyup change', count); return this; };});獲取字節(jié)數(shù)函數(shù)
var lenFor = function(str){ var byteLen=0,len=str.length; if(str){ for(var i=0; i<len; i++){ if(str.charCodeAt(i)>255){ byteLen += 3; } else{ byteLen++; } } return byteLen; } else{ return 0; }}2.實例化
<script type="text/javascript">// demo$(function($){ // 批量 $('.autoTxtCount').each(function(){ $(this).find('.text1').artTxtCount($(this).find('.tips'), 108); });});</script>3.相應的html結構
<div class="form-group"> <div class="col-sm-9"> <label class="col-sm-1 control-label" for="form-field-1"> 內(nèi)容: </label> </div></div><div style="padding-left:100px;" id="autoTxtCount" class="autoTxtCount form-group"> <div > <textarea class="text1" name="content" cols="50" rows="3"><!--{$aData.content}--></textarea> </div> <div> <span class="tips"></span> </div></div>4.一些樣式
#autoTxtCount { width:500px; }#autoTxtCount .help, #autoTxtCount .help a { color:#999; }#autoTxtCount .tips { color:#999; padding:0 5px; }#autoTxtCount .tips strong { color:#1E9300; }#autoTxtCount .tips .js_txtFull strong { color:#F00; }#autoTxtCount textarea.text1 { width:474px; }效果如下:


更多關于jQuery相關內(nèi)容可查看本站專題:《jQuery擴展技巧總結》、《jQuery字符串操作技巧總結》、《jQuery操作xml技巧總結》、《jQuery常見經(jīng)典特效匯總》、《jquery選擇器用法總結》及《jQuery常用插件及用法總結》
希望本文所述對大家jQuery程序設計有所幫助。
新聞熱點
疑難解答