<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>微博</title> <style> body { font-size: 12px; } .box { width: 600px; height: 160px; border: 8px solid pink; margin: 0 auto; padding: 10px; } img { float: left; } .box-num { float: left; margin-left: 255px; width: 150px; height: 24px; font-size: 14px; text-align: right; color: #888; } .box-num span { font-size: 16px; font-weight: bold; } #text { width: 594px; height:100px; border: 1px solid #ccc; margin-top: 5px; clear: both; } .box .item1, .item2, .item3, .item4, .item5, .item6 { float: left; width: 30px; height: 36px; line-height: 32px; padding-left: 26px; } .item1 { background: url(images/an5.png) no-repeat left center; } .item2 { background: url(images/an4.png) no-repeat left center; } .item3 { background: url(images/an3.png) no-repeat left center; } .item4 { background: url(images/an2.png) no-repeat left center; } .item5 { background: url(images/an1.png) no-repeat left center; width: 40px; } .item6 { margin-left: 160px; margin-right: 14px; color: #888; } #but { float: left; border: none; background: #ff6500; color: #fff; width: 80px; height: 30px; border-radius: 5px; } </style> <script> var text, number, m, but; window.onload = function() { text = document.getElementById('text'); number = document.getElementById('number'); but = document.getElementById('but'); text.focus(); text.onkeyup = function aa() { m = 140 - text.value.length; if (m < 0) { number.style.color = 'red'; } else { number.style.color = '#888'; } number.innerHTML = m; } but.onclick = function() { if (text.value == "") { alert('你没有输入内容'); text.focus(); } else if (m < 0) { alert('你输入的内容超过了140个字'); text.focus(); } else { alert('发布成功') } } a(); } </script> </head> <body> <div class="box"> <img src="images/12.png"> <div class="box-num">还可以输入<span id="number">140</span>字</div> <textarea id="text"></textarea> <span class="item1">表情</span> <span class="item2">图片</span> <span class="item3">视频</span> <span class="item4">话题</span> <span class="item5">长微博</span> <span class="item6">公开</span> <input type="button" value="发布" id="but"> </div> </body> </html>
如果按钮提交if语句使用 m==8,默认进入不进行操作点击提交按钮,会提示发布成功,使用text.value == "",就不会出现这个问题。