为输入框添加字数提示
计算字符串长度,中文1,其他0.5:
1 var getByteLen=function(str) { 2 if (str == null) return 0; 3 if (typeof str != "string") { 4 str += ""; 5 } 6 var count_hanzi = str.replace(/[^\x00-\xff]/g, "01").length - str.length; 7 var count_feihanzi = str.length - count_hanzi; 8 return parseInt(count_feihanzi / 2) + count_hanzi; 9 }
设置字数提示:
1 $.fn.TextBoxInputLengthPrompt = function (maxLength) { 2 var obj = $(this); 3 var width_obj = parseInt(obj.width()); 4 var height_obj = parseInt(obj.height()); 5 var top_obj = parseInt(obj.offset().top); 6 var left_obj = parseInt(obj.offset().left); 7 var length_curr =getByteLen(obj.val()); 8 var length_maxLength = maxLength; 9 var div = $('<div></div>'); 10 obj.parent().append(div); 11 div.css({ 12 'width': '180px', 13 'height': '20px' 14 }); 15 div.text('字数:' + length_curr + '/' + length_maxLength); 16 obj.keyup(function () { 17 length_curr = getByteLen(obj.val()); 18 div.text('字数:' + length_curr + '/' + length_maxLength); 19 }) 20 return obj; 21 }
调用:
1 $(selector).TextBoxInputLengthPrompt(count);