var wordsToBeTyped = document.querySelector(‘h2’)。innerHTML.split(’’);var place = 0;var wrong = 0;var correct = 0;document.onkeydown = function(event){
if(event.key === wordsToBeTyped […
这里有一些错误......
避免玩 innerHTML 尽你所能地。 innerHTML 因为getter将返回Element中的所有标记,并且作为setter将删除其中的所有节点。
innerHTML
对你而言,这是一个问题,因为你确实改变了你的元素的innerHTML:在每个角色,你要转换下一个字母作为一个类型 <span class="highlithed"> 。所以当你检查indexOf字符时 (space), you find the one you did add in this markup.
<span class="highlithed">
To avoid that, use the textContent 您的元素的属性,将忽略所有标记。 但是,也不要使用 indexOf 要知道你在哪里,当一个角色出现之前它仍然会失败。所以简单地使用 place 反击你已经有了。
textContent
indexOf
place
// grab textContent var wordsToBeTyped = document.querySelector('h2').textContent.split(''); var place = 0; var wrong = 0; var correct = 0; document.onkeydown = function(event) { event.preventDefault(); if (event.key === wordsToBeTyped[place]) { correct = correct + 1; place = place + 1; // set textContent document.getElementById('correct').textContent = 'Correct: You have ' + correct + ' correct!' } else { wrong = wrong + 1; // set textContent document.getElementById('wrong').textContent = 'Wrong: You have ' + wrong + ' wrong' document.body.style.backgroundColor = 'red'; setTimeout(function() { document.body.style.backgroundColor = 'skyblue' }, 500) } highlight(wordsToBeTyped[place]) } highlight(wordsToBeTyped[place]) function highlight(text) { var inputText = document.querySelector('#checking'); // grab textContent var innerText = inputText.textContent; if (place >= 0) { innerText = "<span class='highlight'>" + innerText.substring(0, place) + innerText.substring(place, place + text.length) + "</span>" + innerText.substring(place + text.length); // here you can set innerHTML inputText.innerHTML = innerText; } }
h3 { display: inline-block; } body { background-color: skyblue; text-align: center; } .highlight { background: yellow; }
<h1>Typing Accuracy Test</h1> <h2 id="checking">lorem ipsum dolor sit amet, tritani debitis ea ius, nostrud albucius vis eu. civibus consequuntur cum ut, te albucius accusamus per, illum nominati temporibus nec eu. adversarium efficiantur ei qui. at vix falli tollit. an graece vituperata vix, iusto primis ponderum id eum, delenit definiebas vix in.</h2> <h3 id="correct"></h3> <h3 id="wrong"></h3>
您正在检查纯文本更改,并且您没有考虑到您的位置 place 。您应该指定为文本,而不是 innerHTML 。也许你应该解析 wordsToBeTyped 作为DOM元素并获取它的内部文本值。
wordsToBeTyped