摘要:<html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0&qu
<html lang="en"> <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> </head> <style> * { margin: 0; padding: 0; } body { font-family: "Microsoft YaHei"; } ul, li { list-style: none; } .box { width: 600px; height: 200px; border: solid 1px #333; margin: 0 auto; } .num span{ font-weight: bold; } textarea { width: 100%; height: 150px; resize: none; outline: none; border: none; } #btn { width: 60px; float: right; text-align: center; border-left: solid 1px #333; line-height: 28px; cursor: pointer; } </style> <body> <div class="box"> <div class="num">還可以輸入<span>140</span>個字</div> <textarea name="" id="text" cols="30" rows="10"></textarea> <div id="btn">提交</div> </div> <script> (function () { var oText = document.getElementById('text'), //輸入區(qū) oNum = document.querySelector('.num span'), //字數顯示區(qū) oBtn = document.getElementById('btn'), //點擊發(fā)布區(qū) num = null; //初始化剩余字數 oText.onkeyup = init; //鍵盤事件 function init() { num = 140 - oText.value.length; //總限制字數 - 以輸入字數 = 剩余字數 oNum.innerHTML = num; //顯示剩余字數 oBtn.onclick = Sub; //點擊事件 if(num<0){ oNum.style.color = "red";//超出字數后,計數文字變紅 }else{ oNum.style.color = "black";//未超出字數,文字變黑 } function Sub() { //字數判斷 if (num == 140) { //沒有輸入文字 console.info("沒有輸入"); } else if (num < 0) { //剩余可輸入文字為負數 console.error("超出字數限制"); } else { //符合發(fā)布要求 console.log("發(fā)布成功"); } } } init(); //初始化 })(); </script> </body> </html>
有注釋了,事件單分了。哈!
批改老師:西門大官人批改時間:2019-03-03 14:10:58
老師總結:不錯,函數的定義可以放到初始化函數外面定義,使用的時候直接調用就行。