(有很多地方没有完善,只是一个基础框架。。。算难的点应该是打字速度的计算吧。)
CSS:
<style> * { text-align: center; } #a { text-align: center; } #a div { display: inline-block; margin: 0 30px; } #abc { text-align: center; font-size: 50px; background-color: pink; } </style>
HTML:
<body> <div id="a"> <div>true:0</div> <div>false:0</div> </div> <div id="abc"> 准备好了吗? </div> <button>开始</button> <button>刷新</button> <div>您的打字速度大约是:0个/分钟</div> </body>
JavaScript:
<script> let end = document.querySelectorAll("div"); let but = document.querySelectorAll("button"); let abc = document.querySelector("#abc"); let a = document.querySelector("#a").querySelectorAll("div"); let num = []; let font = []; let t = 0; let f = 0; let i = 0; let z = 0; //刷新页面 but[1].onclick = function () { location.reload(); } but[0].onclick = function () { //点击“开始”获取开始时间 let startTime = new Date(); let sTime = startTime.getSeconds(); console.log(sTime); for (let i = 0; i < 10; i++) { //输出随机字母的ASCII码 let x = Math.floor(Math.random() * 26 + 65); //将ASCII码放入数组num,方便以后比对 num.push(x); //将ASCII码对应的字母放入数组font,方便等下打印 font.push(String.fromCharCode(x)); } //输出文字 abc.innerHTML = font; //添加键盘监听器 document.addEventListener("keyup", function (e) { if (e.keyCode === num[i]) { t++; a[0].innerHTML = "true:" + t; i++; } else { f++; a[1].innerHTML = "false:" + f; } //当打完字时获取结束时间 if (t == 10) { let endTime = new Date(); let eTime = endTime.getSeconds(); console.log(eTime); //获取的结束时间有可能跟开始时间不是同一分钟,加个if判断 if (eTime - sTime < 0) { z = parseInt(600 / (eTime + 60 - sTime)); end[end.length - 1].innerHTML = "您的打字速度大约是:" + z + "个/分钟"; } else { z = parseInt(600 / (eTime - sTime)); end[end.length - 1].innerHTML = "您的打字速度大约是:" + z + "个/分钟"; } console.log(z); } }) //将开始按钮禁用,就可以避免数据出错 this.disabled = true; } </script>
记录一下学习过程。。。