javascript - 我无法控制台记录最后一个块输出?为什么会发生?
问题描述
我已经编写了代码来递归地闪烁块,并在我按下任意键时控制台记录块的名称。除了最后一个键,每个块都在控制台中打印,而且我想运行一个函数,在文档中渲染一个圆圈,在控制台中显示文本,并在圆圈显示时使按钮消失。我怎样才能做到这一点?(LMNO 不在控制台中打印)
let curr_div_on = 0,curr_div_off = 0;
const key = document.getElementsByClassName("key");
function setPlayingOn() {
key[curr_div_on % 4].classList.add("playing");
curr_div_on = (curr_div_on + 1) % 4;
}
function setPlayingOff() {
key[curr_div_off % 4].classList.remove("playing");
curr_div_off = (curr_div_off + 1) % 4;
}
setInterval(setPlayingOn, 500);
setTimeout(() => setInterval(setPlayingOff, 500), 500);
document.addEventListener('keypress', function(){
if(curr_div_on==1){
console.log('ABCD');
}else if(curr_div_on==2){
console.log('EFGH');
}else if(curr_div_on==3){
console.log('IJKL');
}else if(curr_div_on==4){
console.log('LMNO');
}
})
.grid{
display: grid;
grid-template-columns: auto auto;
grid-gap:10px;
}
.key{
padding: 20px;
border: 1px solid;
background-color: #2196F3;
text-align:center;
}
.playing{
transform: scale(1,1);
border-color: #ffc600;
box-shadow: 0 0 1rem #ffc600;
}
<html>
<div class='grid'>
<button class='key'>ABCD</button>
<button class='key'>EFGH</button>
<button class='key'>IJKL</button>
<button class='key'>LMNO</button>
</div>
</html>
解决方案
您不能拥有多个具有相同 id 的元素,id 必须是唯一的。您可以改用一个类。
let curr_div_on = 0,curr_div_off = 0;
const key = document.getElementsByClassName("key");
function setPlayingOn() {
key[curr_div_on % 4].classList.add("playing");
curr_div_on = (curr_div_on + 1) % 4;
}
function setPlayingOff() {
key[curr_div_off % 4].classList.remove("playing");
curr_div_off = (curr_div_off + 1) % 4;
}
setInterval(setPlayingOn, 500);
setTimeout(() => setInterval(setPlayingOff, 500), 500);
.grid{
display: grid;
grid-template-columns: auto auto;
grid-gap:10px;
}
.key{
padding: 20px;
border: 1px solid;
background-color: #2196F3;
text-align:center;
}
.playing{
transform: scale(1,1);
border-color: #ffc600;
box-shadow: 0 0 1rem #ffc600;
}
<html>
<div class='grid'>
<div class='key'>A</div>
<div class='key'>B</div>
<div class='key'>C</div>
<div class='key'>D</div>
</div>
</html>
推荐阅读
- python - Python - 将默认字符串分配给 1 和 0
- amazon-s3 - create-react-app:从 CDN 提供 index.html 并在新版本发布后加载正确的静态资产
- pandas - 根据 pandas 中的给定条件随机对数据进行子集化
- java - 如何使用Java代码使用一个对象将三个字段存储在ArrayList中?
- sql - 如何在 SQL 查询更新中传递变量
- mysql - 如何从 Visual Studio Code 连接到 MySQL 服务器
- c# - 从 WSDL 更改生成的服务引用调用的 HTTP 主机头
- sql - 过滤子查询性能问题
- node.js - 如果节点关闭,如何在多个节点上处理 socketio
- sql - 地理坐标在原始 GPS 表中时如何获取出行方式