如何在 JavaScript 中发送字母数组的按键

我正在尝试想出一种解决方案,可以虚拟按键进行打字测试。我想要的是获取文本并将各个字母存储在数组中,然后按下所有键,每次按下之间有一些延迟。


这是文本布局的 HTML。想象一下它有这个词hello。


<div class="digit-container">

    <div>

        <span>h</span>

    </div>

</div>

<div class="digit-container">

    <div>

        <span>e</span>

    </div>

</div>

<div class="digit-container">

    <div>

        <span>l</span>

    </div>

</div>

<div class="digit-container">

    <div>

        <span>l</span>

    </div>

</div>

<div class="digit-container">

    <div>

        <span>o</span>

    </div>

</div>


这是我想出的 JavaScript 代码。我已经设法将这些字母存储在一个数组中。


wordList = document.querySelectorAll(".digit-container > div > span");

wordArray = [];


for (let i = 0; i < wordList.length; i++) {

    individualWord = wordList[i].innerHTML;

    wordArray.push(individualWord);

}

现在我希望 JavaScript 发送这个字母数组 { "h", "e", "l", "l", "o" } 的按键。基本上,当我粘贴此代码并在控制台中按 Enter 键时,我希望 JavaScript 在击键之间有几毫秒的延迟按“Hello”。如何将 JavaScript 放入按键中?


冉冉说
浏览 82回答 1
1回答

德玛西亚99

这是解决方案。const elements = document.querySelectorAll(".digit-container > div > span");const chars = Array.from(elements).map((item) => item.textContent);const delay = 1000;let i = 0;const pressKey = () => {&nbsp; setTimeout(() => {&nbsp; &nbsp; const char = chars[i];&nbsp; &nbsp; const event = new KeyboardEvent("keyup", {&nbsp; &nbsp; &nbsp; key: char&nbsp; &nbsp; });&nbsp; &nbsp; document.body.dispatchEvent(event);&nbsp; &nbsp; if (i !== chars.length - 1) {&nbsp; &nbsp; &nbsp; i++;&nbsp; &nbsp; &nbsp; pressKey();&nbsp; &nbsp; }&nbsp; }, delay);};pressKey();document.body.addEventListener("keyup", (e) => {&nbsp; console.log(e.key);});<div class="digit-container">&nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; <span>h</span>&nbsp; &nbsp; </div></div><div class="digit-container">&nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; <span>e</span>&nbsp; &nbsp; </div></div><div class="digit-container">&nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; <span>l</span>&nbsp; &nbsp; </div></div><div class="digit-container">&nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; <span>l</span>&nbsp; &nbsp; </div></div><div class="digit-container">&nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; <span>o</span>&nbsp; &nbsp; </div></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript