我正在参加「码上掘金挑战赛」详情请看:码上掘金挑战赛来了!
打字机模仿
详细代码展示
板块简绍
1.有三个小方块,分别用来当前输入的错误数量、打字的时间和当前的正确率。
2.下方是用来显示测试句子的容器。
3.最后是输入框
具体思路:
点击输入文本区域时,开始测试,会根据用户输入来统计当前的错误数和正确率,时间会减少。当输完整段句子时,会自动更新下一段句子。当时间为0时,游戏结束,文本框不能再输入,然后会统计打字速度。
具体代码解释
1.打字规划
时间60秒,六句话
var testTime = 60;
//定义测试的句子
var testSentence = [
"Push yourself, because no one else is going to do it for you.",
"Failure is the condiment that gives success its flavor.",
"Wake up with determination. Go to bed with satisfaction.",
"It's going to be hard, but hard does not mean impossible.",
"Learning never exhausts the mind.",
"The only way to do great work is to love what you do."
]
2.定义dom
//定义dom
//1.错误dom
var error_text = document.querySelector('.error_text');
//2.时间dom
var time_text = document.querySelector('.time_text');
//3.当前正确率
var currcorrect_text = document.querySelector('.currcorrect_text');
//4.打字速度
var type_speed_text = document.querySelector('.type_speed_text');
//打字速度父dom
var type_speed = document.querySelector('.type_speed');
//句子dom
var text_box = document.querySelector('.text_box');
相关dom解析
注意: querySelector() 方法仅仅返回匹配指定选择器的第一个元素。如果你需要返回所有的元素,请使用 querySelectorAll() 方法替代。
参数类型可以为如下: 指定一个或多个匹配元素的 CSS 选择器。 可以使用它们的 id, 类, 类型, 属性, 属性值等来选取元素。对于多个选择器,使用逗号隔开,返回一个匹配的元素。
3.相关函数解释
进行更新句子
function updateSentence(){
text_box.textContent = null;
currentSentence = testSentence[startIndex];
//句子拆分
var newChar = currentSentence.split('');
for(var i = 0; i < newChar.length; i++){
var charSpan = document.createElement('span');
charSpan.innerText = newChar[i];
text_box.appendChild(charSpan)
}
if(startIndex < testSentence.length - 1){
startIndex++;
}else{
startIndex = 0
}
}
document.createElement在 HTML 文档中,Document.createElement() 方法用于创建一个由标签名称 tagName 指定的 HTML 元素。如果用户代理无法识别 tagName,则会生成一个未知 HTML 元素 HTMLUnknownElement
输入函数,进行输入的判断,以及进行调整相关内容
//当前没有输入
if(typeChar == null){
char.classList.remove('correct_char');
char.classList.remove('incorrect_char');
}else if(typeChar === char.innerText){
//正确的输入
char.classList.add('correct_char');
char.classList.remove('incorrect_char');
}else{
//不正确的输入
char.classList.add('incorrect_char');
char.classList.remove('correct_char');
errors++;
}