. 代碼如下:
<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>