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>個(gè)字</div> <textarea name="" id="text" cols="30" rows="10"></textarea> <div id="btn">提交</div> </div> <script> (function () { var oText = document.getElementById('text'), //輸入?yún)^(qū) oNum = document.querySelector('.num span'), //字?jǐn)?shù)顯示區(qū) oBtn = document.getElementById('btn'), //點(diǎn)擊發(fā)布區(qū) num = null; //初始化剩余字?jǐn)?shù) oText.onkeyup = init; //鍵盤(pán)事件 function init() { num = 140 - oText.value.length; //總限制字?jǐn)?shù) - 以輸入字?jǐn)?shù) = 剩余字?jǐn)?shù) oNum.innerHTML = num; //顯示剩余字?jǐn)?shù) oBtn.onclick = Sub; //點(diǎn)擊事件 if(num<0){ oNum.style.color = "red";//超出字?jǐn)?shù)后,計(jì)數(shù)文字變紅 }else{ oNum.style.color = "black";//未超出字?jǐn)?shù),文字變黑 } function Sub() { //字?jǐn)?shù)判斷 if (num == 140) { //沒(méi)有輸入文字 console.info("沒(méi)有輸入"); } else if (num < 0) { //剩余可輸入文字為負(fù)數(shù) console.error("超出字?jǐn)?shù)限制"); } else { //符合發(fā)布要求 console.log("發(fā)布成功"); } } } init(); //初始化 })(); </script> </body> </html>
有注釋了,事件單分了。哈!
Correcting teacher:西門(mén)大官人Correction time:2019-03-03 14:10:58
Teacher's summary:不錯(cuò),函數(shù)的定義可以放到初始化函數(shù)外面定義,使用的時(shí)候直接調(diào)用就行。