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('\u8FD8\u80FD\u8F93\u5165 ' + (maxNumber - val) + ' \u4E2A\u5B57\u8282'); }else{ tipWrap.html('\u5DF2\u7ECF\u8D85\u51FA ' + (val - maxNumber) + ' \u4E2A\u5B57\u8282'); }; }; $(this).bind('keyup change', count); return this; }; });
获取字节数函数
var lenFor = function(str){ var byteLen=0,len=str.length; if(str){ for(var i=0; i255){ byteLen += 3; } else{ byteLen++; } } return byteLen; } else{ return 0; } }
2.实例化
3.相应的html结构
#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; }