<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>javascript学习之textarea控制输入字数限制</title> <style type="text/css"> body{font-size: 12px;} .box{width: 600px; height: 160px; border:8px solid pink; margin: 0px auto;padding: 10px;} .box1{float:right; margin-left: 255px; width: 150px; height: 25px; text-align: right;font-size: 14px; color: #888;} .box1 span{font-size: 16px; font-weight: bold;} #text{width: 600px;height: 100px;border: 1px solid #888;margin-top: 5px;} .box #sp1,#sp2,#sp3,#sp4,#sp5,#sp6{float: left;width: 30px;height: 32px;line-height: 32px;padding-left: 26px;} #sp5{width: 40px;} #sp6{margin-left: 150px; margin-right: 15px; color: #888;} #bt{float:left; width: 80px; height: 30px; border: none; background:#ffc09f; color: #fff; border-radius: 5px;} </style> <script type="text/javascript"> var text; var number; var m; window.onload = function(){ text = document.getElementById('text'); number = document.getElementById('number'); bt = document.getElementById('bt'); text.onkeyup = function aa(){ m = 140 - text.value.length; //限制字数 if(m < 0){ number.style.color = 'red'; }else{ number.style.color = '#888'; } number.innerHTML = m; } bt.onclick = function(){ if(m==140){ alert('您还没有输入内容!'); text.focus(); }else if(m < 0){ alert('您的内容超过限制字数!'); text.focus(); }else{ alert('发布成功!'); } } aa(); } </script> </head> <body> <div class="box"> <div class="box1">还可以输入<span id="number">140</span>字</div> <textarea id="text"></textarea> <span id="sp1">表情</span> <span id="sp2">图片</span> <span id="sp3">视频</span> <span id="sp4">话题</span> <span id="sp5">长微薄</span> <span id="sp6">公开</span> <input type="button" value="发布" id="bt" name=""> </div> </body> </html>