摘要:<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>輸入字?jǐn)?shù)</title> <style> *{margin: 0;padding: 0;} textarea{
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>輸入字?jǐn)?shù)</title> <style> *{margin: 0;padding: 0;} textarea{margin: 100px auto 0;display: block;background: #aefffe;} button{width: 80px;height: 30px;background:blue;border-radius: 3px;color:white;margin: 20px auto 0;display: block;} button:hover{cursor: pointer;} div div{width: 400px;margin:20px auto;} </style> </head> <body> <div id="txt"> <textarea id="txtInput" cols="100" rows="10" onkeyup="txtChange()" placeholder="請輸入文字"></textarea><br> <div><span>您已輸入</span><span id="txtCount">0</span><span>個(gè)字符,還可以輸入</span><span id="txtLeft">140</span><span>個(gè)字符</span></div> <button id="mysubmit" type="button" onclick="mysubmit()">提交</button> </div> </body> <script> var txtCount = document.getElementById("txtCount"); var txtInput = document.getElementById("txtInput"); var txtLeft = document.getElementById("txtLeft"); function txtChange(){ txtCount.innerText=txtInput.value.length; txtLeft.innerText = 140-txtInput.value.length; } function mysubmit(){ if(txtLeft.innerText==140){ alert("輸入不能為空"); }else if(txtLeft.innerText<0){ alert("不能超過140字"); }else{alert("提交成功")}; } </script> </html> ------------------------- 效果圖 -------------------------
思路:
1、兩個(gè)span用于實(shí)時(shí)計(jì)數(shù)
2、js獲取文本域的值的長度
3、onkeyup事件觸發(fā)給span文本賦值上一步獲取的文本長度
4、點(diǎn)擊提交按鈕時(shí),對字?jǐn)?shù)進(jìn)行判斷,字?jǐn)?shù)為零或字?jǐn)?shù)超過140時(shí),彈出警告信息
批改老師:天蓬老師批改時(shí)間:2019-04-13 21:55:24
老師總結(jié):你的變量與函數(shù)的命名非常的規(guī)范, 事件也運(yùn)行的正確...
順便說一下,微博早已取消字?jǐn)?shù)限制了