abstract:<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'), //输入区 oNum = document.querySelector('.num span'), //字数显示区 oBtn = document.getElementById('btn'), //点击发布区 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 { //符合发布要求 console.log("发布成功"); } } } init(); //初始化 })(); </script> </body> </html>
有注释了,事件单分了。哈!
Correcting teacher:西门大官人Correction time:2019-03-03 14:10:58
Teacher's summary:不错,函数的定义可以放到初始化函数外面定义,使用的时候直接调用就行。