サマリー:<style type="text/css"> .wb{border: solid 10px pink; width: 600px;height: 170px;margin: 0 auto;padding: 15px;} .clear{clear: both
<style type="text/css"> .wb{border: solid 10px pink; width: 600px;height: 170px;margin: 0 auto;padding: 15px;} .clear{clear: both;} .wb .logo{float: left;} .wb .tit{float: right;} .wb #area{width: 600px;height: 100px;margin-top: 15px;} .wb .box span{width: 40px;height: 32px; line-height: 32px; padding-left: 25px;} .wb .box1{background: url(wbimg/an5.png) no-repeat left center;} .wb .box2{background: url(wbimg/an4.png) no-repeat left center;} .wb .box3{background: url(wbimg/an3.png) no-repeat left center;} .wb .box4{background: url(wbimg/an2.png) no-repeat left center;} .wb .box5{background: url(wbimg/an1.png) no-repeat left center;} .wb .box6{padding-left: 120px!important;} .wb #bt{border: none;width: 80px;height: 32px;line-height: 32px;background-color: orange;color: #fff;border-radius: 5px;float: right;cursor: pointer;font-weight: bold;} </style>
<div class="wb"> <img src="wbimg/12.png" class="logo"> <div class="tit">還可以輸入 <span id="number">140</span> 字</div> <div class="clear"></div> <textarea name="area" id="area"></textarea> <div class="box"> <span class="box1">表情</span> <span class="box2">圖片</span> <span class="box3">視頻</span> <span class="box4">話題</span> <span class="box5">長微博</span> <span class="box6">公開</span> <input type="button" name="bt" value="發(fā)布" id="bt"> </div> </div>
<script type="text/javascript"> var area,number,m; window.onload = function(){ area = document.getElementById('area'); //area是獲取輸入框的內(nèi)容 number = document.getElementById('number'); //number是獲取還可以輸入多少字的數(shù)字內(nèi)容 bt = document.getElementById('bt'); area.onkeyup = function (){ m = 140-area.value.length; //m是總字數(shù)-當前輸入字數(shù),即還可以輸入的多少字數(shù) if(m<0){ //如果剩余輸入字數(shù)少于0,即負值,就變換個顏色 number.style.color='red'; }else{ number.style.color='#666'; } number.innerHTML=m; // 把剩余輸入字數(shù)賦值給number元素 } bt.onclick = function(){ if(m == 140){ alert("你還沒有輸入"); }else if(m<0){ alert("您輸入字數(shù)過多,可輸入最多140字"); }else{ alert("發(fā)布成功!"); } } } </script>
總結:用規(guī)定的字數(shù)(140)減去獲取(onkeyup)輸入框的字數(shù),得到還可輸入的字數(shù)(變量m),最后賦值給獲取的number。在對number做完善的判斷處理。和提交的判斷處理。
注意下:getElementById("id名") 獲取指定元素
getElementsByClassName("class名") 獲取class元素
getElementsByTagName("標簽名") 獲取class元素
因為id是唯一的,所以Element后面不加s,其他獲取的均為集合,加s
添削の先生:天蓬老師添削時間:2019-03-28 17:19:03
先生のまとめ:這和剛才應該是同一個作業(yè)的二個部分, 其實現(xiàn)在很多的UI組件,都自帶有統(tǒng)計字數(shù)的文本域控件的, 不過, 了解字數(shù)的統(tǒng)計原理, 還是有必要的