很多表單都需要限制輸入字數——標題不能超過 50 字、評論不能超過 200 字。做一個即時顯示「您還可以輸入 N 個字」的計數器,難點不在長度計算,而在換行符的處理:textarea 裡的 Enter,送到後端後其實是 \r\n 兩個字元。
/*
*長度跟蹤器
*v2.1.0
*bind2Id:用於顯示長度變化的元素的id
*max:最大長度
*msgWrap:提示信息(必須要有一個"-"占位符)
*eg:$('#input').lenTracer({bind2Id:'myTracer',max:150,msgWrap:'您還可以輸入-個字符'});
*author:liujg1015@gmail.com
*/
(function ($) {
var zw_validate = function (el, option) {
this.el = $(el);
this.bindEl = false;
this.setting = {
bind2Id: false,
max: 100,
msgWrap: '您還可以輸入-個字符'
};
if (option) {
$.extend(this.setting, option);
this.init();
}
};
zw_validate.prototype = {
init: function () {
var _this = this;
this.bindEl = $('#' + this.setting.bind2Id);
this.el.focus(function () { _this.start(); }).blur(function () { _this.dispose(); });
this.el.css({ paddingBottom: 20 });
this.initMsg();
},
initMsg: function () {
var wrap = this.setting.msgWrap.split('-');
this.bindEl.text(this.setting.max - this.count().total).before(wrap[0]).after(wrap[1]);
},
count: function () {
var _val = this.el.val();
var _len = _val.length;
var _rowCount = 0;
var _enterLen = 0;
var _partten = /\n+/g;
if (_len > 0 && _partten.test(_val)) {
_enterLen += 3;
while ((result = _partten.exec(_val)) != null) {
if ((result.index + 1 + _enterLen) > this.setting.max) {
break;
}
_enterLen += 3;
}
_rowCount = _val.match(_partten).length;
}
return { total: (_len + _rowCount * 3), enterLen: _enterLen };
},
start: function () {
var _this = this;
_this.timer = setInterval(function () {
var _val = _this.el.val();
var _rlt = _this.count();
if (_rlt.total > _this.setting.max) {
if (_rlt.enterLen > 0) {
_this.el.val(_val.substr(0, _this.setting.max - _rlt.enterLen));
}
else {
_this.el.val(_val.substr(0, _this.setting.max));
}
_this.bindEl.text(_this.setting.max - _this.count().total);
return;
}
_this.bindEl.text(_this.setting.max - _rlt.total);
}, 300);
},
dispose: function () {
clearInterval(this.timer);
},
restore: function () {
this.bindEl.text(this.setting.max - this.el.val().length);
}
};
$.fn.extend({
lenTracer: function (option) {
return new zw_validate(this, option);
}
});
})(jQuery);
先把上面的腳本存成 lentracer.js,然後在頁面中引入 jQuery 與它:
<html>
<head>
<title>demo</title>
</head>
<body>
<table>
<tr>
<td>
標題
</td>
<td>
<input type="text" id="title" />
<span id="titlelen"></span>
</td>
</tr>
<tr>
<td>
評論
</td>
<td>
<textarea cols="5" rows="5" id="comment"></textarea>
<span id="commentlen"></span>
</td>
</tr>
</table>
<script src="../scripts/jquery.js" type="text/javascript"></script>
<script src="../scripts/lentracer.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#title').lenTracer({ bind2Id: titlelen, max: 50});
$('#comment').lenTracer({ bind2Id: commentlen, max: 200, msgWrap: '剩余-字' });
});
</script>
</body>
</html>
這是整個插件最值得說明的地方。使用者在 textarea 按一次 Enter,畫上看起來只佔一個位置,但字串裡實際多了 \r\n 兩個字元,而送到伺服器端後,若資料庫欄位或後端語言再作轉換,長度計算又可能不同。程式碼採取的策略是:每個換行額外多算 3,用比較保守的估值把這些轉換的膨脹提前扣掉,避免前端說「還能打 5 個字」、後端卻回「超出限制」的尷尬。
enterLen 的計算則是為了另一件事:當內容超限需要截斷時,不能天真地從頭截到 max 就好,否則可能把換行符截成半個。程式碼遍歷每個換行位置,找出「截斷點不會切斷換行」的合法位置,再用它來決定要保留多少字。
第一,用 setInterval 每 300 毫秒輪詢一次來更新計數,其實沒必要——直接監聽 keyup、input 事件即可,更即時也更省資源。輪詢的代價是使用者停止打字後,數字還會慢半拍才更新。
第二,範例的最後兩行有語法錯誤:$('#title).lenTracer(...) 少了右引號,應為 $('#title');bind2Id: titlelen 也應寫成字串 'titlelen'。
第三,用 .val(value) 直接截斷內容會把游標位置推到尾端。若使用者是在中間插入文字導致超限,體驗會很突兀;較好的做法是取得 selectionStart,截斷後再把游標設回合理位置。
這個計數器是我自己用 jQuery 寫的,因此依賴 jQuery 函式庫。歡迎批評指正。