jQuery计算textarea中文字数(剩余个数)的小程序
代码如下:
<div class="area"> <p> 还可以输入<b class="num">140</b>字</p> <textarea class="chackTextarea"></textarea> </div> <script type="text/javascript"> var txtobj = { divName: "area", //外层容器的class textareaName: "chackTextarea", //textarea的class numName: "num", //数字的class num: 140 //数字的最大数目 } var textareaFn = function () { //定义变量 var $onthis; //指向当前 var $divname = txtobj.divName; //外层容器的class var $textareaName = txtobj.textareaName; //textarea的class var $numName = txtobj.numName; //数字的class var $num = txtobj.num; //数字的最大数目 function isChinese(str) { //判断是不是中文 var reCh = /[u00-uff]/; return !reCh.test(str); } function numChange() { var strlen = 0; //初始定义长度为0 var txtval = $.trim($onthis.val()); for (var i = 0; i < txtval.length; i++) { if (isChinese(txtval.charAt(i)) == true) { strlen = strlen + 2; //中文为2个字符 } else { strlen = strlen + 1; //英文一个字符 } } strlen = Math.ceil(strlen / 2); //中英文相加除2取整数 if ($num - strlen < 0) { $par.html("超出 <b style='color:red;font-weight:lighter' class=" + $numName + ">" + Math.abs($num - strlen) + "</b> 字"); //超出的样式 } else { $par.html("还可以输入 <b class=" + $numName + ">" + ($num - strlen) + "</b> 字"); //正常时候 } $b.html($num - strlen); } $("." + $textareaName).live("focus", function () { $b = $(this).parents("." + $divname).find("." + $numName); //获取当前的数字 $par = $b.parent(); $onthis = $(this); //获取当前的textarea var setNum = setInterval(numChange, 500); }); } textareaFn(); </script>
相关推荐
81971235 2017-03-23
zengni 2020-04-16
Vipwxs 2018-12-19
javaer 2008-09-02
jscjxysx 2019-07-01
冯二爷 2019-07-01
Donutsapps 2019-06-29
无情 2018-12-19
87281248 2017-09-28
原為簡單 2017-09-28
web开发 2017-01-16
勤能补拙孰能生巧 2019-06-28
wndong 2015-12-14
shishaoe 2015-04-10
csstpeixun 2015-04-02
xiaocaibai 2014-12-19
realitycss 2014-05-05
DreamLee 2013-12-13
切慕溪水 2013-07-11