您好,欢迎访问一九零五行业门户网

jQuery扩展实现text提示还能输入多少字节的方法

本文实例讲述了jquery扩展实现text提示还能输入多少字节的方法。分享给大家供大家参考,具体如下:
1.添加jquery自定义扩展
$(function($){ // tipwrap: 提示消息的容器 // maxnumber: 最大输入字符 $.fn.arttxtcount = function(tipwrap, maxnumber){ var countclass = 'js_txtcount', // 定义内部容器的css类名 fullclass = 'js_txtfull', // 定义超出字符的css类名 disabledclass = 'disabled'; // 定义不可用提交按钮css类名 // 统计字数 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; }; });
获取字节数函数
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"> 内容: </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; }
效果如下:
其它类似信息

推荐信息