當(dāng)我們開發(fā)一個(gè)網(wǎng)頁(yè)時(shí),經(jīng)常會(huì)涉及到輸入框的開發(fā)。由于數(shù)據(jù)庫(kù)字符字段的限制,往往會(huì)對(duì)文字?jǐn)?shù)量有所限制。如果在輸入框旁邊加上剩余字符的提醒,可以增強(qiáng)用戶體驗(yàn)感。那么 JS 如何實(shí)現(xiàn)輸入框文字剩余字?jǐn)?shù)提醒呢?這篇文章告訴你。
先來看下實(shí)現(xiàn)效果:
源碼如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>W3Cschool-編程獅</title>
<script type="text/javascript" src="./js/jquery.min.js"></script>
</head>
<script type="text/javascript">
$().ready(function(){
var ty = document.getElementById("cty");
var sentence=document.getElementById("sentence");
var minLen=document.getElementById("minLen");
var maxLen=document.getElementById("maxLen");
var leftLen=document.getElementById("leftLen");
sentence.onkeyup= function () {
maxLength = parseInt(maxLen.firstChild.nodeValue);
this.value = this.value.substr(0,maxLength);
var len = this.value.length;
minLen.firstChild.nodeValue = len;
leftLen.firstChild.nodeValue = maxLength-len;
};
});
</script>
<body>
<label>
<textarea name="sentence" id="sentence"></textarea>
<br/>
<em>
<span id="minLen">0</span>/<span id="maxLen">100</span>字,還能輸入<span id="leftLen">100</span>字!
</em>
</label>
</body>
</html>
以上就是 JS 如何實(shí)現(xiàn)輸入框文字剩余字?jǐn)?shù)的全部?jī)?nèi)容。