jquery仿新浪微博限制文本框字数
参考博客:http://www.cnblogs.com/lhb25/archive/2012/11/30/oninput-and-onpropertychange-event-for-input.html
$(function(){ var limitSum = 140;//限制的字数 var showWords = $("#showWords"); //文本框获得焦点和失去焦点时的事件 $("#txt").focus(function(){ if($(this).val() == "") { showWords.show().html("还可以输入"+""+limitSum+""+"个字") .find("span").css({ "font-size":"20px", "color":"green" }); } }).blur(function(){ if($(this).val() == "") { showWords.hide(); } }); //文本输入时改变 $("#txt").on("input propertychange",function(){ var iNum=Math.ceil(getLength($(this).val())/2);//Math函数向上取整,这里统计的是字符数,如果要统计字节数,此处可注释 if(iNum>limitSum) { showWords.html("已经超过"+""+(iNum-limitSum)+""+"个字") .find("span").css({ "font-size":"20px", "color":"red" }); } else{ showWords.html("还可以输入"+""+(limitSum-iNum)+""+"个字") .find("span").css({ "font-size":"20px", "color":"green" }); } }); }); //处理输入的内容是文字还是字母的函数 function getLength(str){ return String(str).replace(/[^\x00-\xff]/g,'aa').length; };