首页 > 解决方案 > 我无法控制台记录最后一个块输出?为什么会发生?

问题描述

我已经编写了代码来递归地闪烁块,并在我按下任意键时控制台记录块的名称。除了最后一个键,每个块都在控制台中打印,而且我想运行一个函数,在文档中渲染一个圆圈,在控制台中显示文本,并在圆圈显示时使按钮消失。我怎样才能做到这一点?(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>

标签: javascripthtmlcssdomcss-transitions

解决方案


您不能拥有多个具有相同 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>


推荐阅读