為輸入框添加字數提示
阿新 • • 發佈:2017-09-30
計算 return func str 輸入框 parse input type byte
計算字符串長度,中文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);
為輸入框添加字數提示