【问题标题】:I am unabel to console log the last block output? why its happening?我无法控制台记录最后一个块输出?为什么会这样?
【发布时间】:2020-11-25 20:51:46
【问题描述】:

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

【问题讨论】:

  • 什么错误,在什么循环中?
  • 您为所有 div 块定义了相同的 id,另外,getElementById 不会返回具有相同 id 的所有块的数组

标签: javascript html css dom css-transitions


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2019-01-30
    • 2011-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-10
    • 2021-09-21
    • 2021-04-06
    • 1970-01-01
    相关资源
    最近更新 更多