实现逻辑:设置定时器每秒刷新一次,定时器刷新多少次执行一次生成单词操作来决定单词的生成速度,例如初始单词生成速度为1,那么定时器刷新5次才生成一次单词,每个单词用span来装,每组10个单词放到div里。监听键盘按下事件,用一个变量str记录键盘连续按下的字母组成的字符串,当字符串str包含span中的字符串,则span变红,同时右下角得分数加1,当div中的一排span都变红时,从body里删掉该div。如果有高中必备3500单词作为单词库,每次生成的一组10个单词从中随机选取,效果更加,既能练习打字又能熟悉单词拼写。
上代码:
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style type="text/css">
span{
font-size: larger;
margin: 20px;
}
#score{
background-color: red;
color: white;
position: absolute;
left:90%;
top: 90%;
}
</style>
</head>
<span id="score">
0
</span>
<body>
<script>
var content = "";
var score = 0;
//这里可以使用固定单词
var words= ["apple","horizontal","vertical","vector","ghost","evil","banana","polo","curve","deploy"];
var str = '';
var count = 0;
//单词生成速度,可以根据当前得分来设置,得分越高速度越快,比如当得分大于200时速度设为2,大于300百是速度设为3
var speed = 1;
setInterval(()=>{
if(count%(6-speed)===0){
let divElement = document.createElement('div');
for (var i = 0; i <words.length ; i++) {
var rand = Math.floor(Math.random()*words.length);
var span = document.createElement('span');
span.innerText = words[rand];
divElement.appendChild(span);
document.body.appendChild(divElement);
}
}
count++;
},1000)
document.addEventListener("keydown",function (event) {
str+=event.key;
console.log(str);
var spans = document.getElementsByTagName('span');
var matchCnt = 0;
for (var i = 0; i <spans.length ; i++) {
if(str.includes(spans[i].innerText)){
spans[i].style.color = 'red'
score++;
matchCnt++;
}
}
if(matchCnt>0){
str = '';
}
document.getElementById('score').innerText = score;
//清除全部打出的一行
var divs = document.getElementsByTagName('div');
for (var i = 0; i <divs.length ; i++) {
var children = divs[i].children;
var redCnt = 0;
for (var j = 0; j <children.length ; j++) {
if(children[j].style.color === 'red'){
redCnt++;
}
}
if(redCnt===children.length){
document.body.removeChild(divs[i]);
}
}
});
</script>
</body>
</html>