常見於發文、留言、標題輸入框:即時顯示已輸入字數與最大限制,超過時以紅色警示。本文示範使用 keyup、click 事件搭配 jQuery 操作 DOM 實現。
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery 統計文字個數</title>
<script src="js/jquery.js"></script>
</head>
<body>
<ul>
<li>
<span>新聞標題:</span>
<input id="news_title" name="news_title" type="text" size="60"
onkeyup="title_len();" onclick="title_len();" maxlength="80" />
<span id="titlelen">0/80</span>
</li>
</ul>
<script>
function title_len() {
var value = $('#news_title').val().length;
var string;
if (value == 80) {
string = '<span style="color:#FF0000">' + value + '/80</span>';
} else {
string = '<span style="color:#FF0000">' + value + '</span>/80';
}
$('#titlelen').html(string);
}
</script>
</body>
</html>
on('input', ...),涵蓋鍵盤、貼上、拖放等所有輸入方式。.over-limit { color: #f00; },JS 僅切換類別。.length 即可;若需按位元組計算,需額外處理。<style>
#titlelen.over { color: #f00; }
</style>
<input id="news_title" maxlength="80" />
<span id="titlelen">0/80</span>
<script>
$('#news_title').on('input', function() {
var len = this.value.length;
var $counter = $('#titlelen');
$counter.text(len + '/80').toggleClass('over', len >= 80);
});
</script>