如何使用getElementsByClassName()添加两个网格并一个接一个地显示? [英] How to use getElementsByClassName() for adding both grids and display one after another?

查看:47
本文介绍了如何使用getElementsByClassName()添加两个网格并一个接一个地显示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  1. 我已经尝试在按一个键时添加grid-2,但是它没有按我预期的那样工作.
  2. 当它显示网格2时,我希望网格消失(我不知道该怎么办).

(背景):-我搜索后发现CSS中有一个可见性属性,但是不知道如何应用于整个网格并撤消可见性属性并使它们可见.

(background):- I have searched and found there is a visibility property in CSS, but don't know how to apply to the whole grid and undo the visibility property and make them visible.

我尝试通过getElementById添加grid-2,但是两个网格同时出现.(不知道如何让它们一个接一个地出现).

I have tried to add the grid-2 by getElementById but both the grids are appearing at a time. (don't know how to make them appear one after another).

let curr_div_on = 0,curr_div_off = 0;


const key = document.getElementsByClassName('keys');


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){
    var element = document.getElementsByClassName("grid-2");
    element.classList.add("grid");
      }
  
})

.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'>ABCD</div>
    <div class='key'>EFGH</div>
    <div class='key'>IJKL</div>
    <div class='key'>LMNO</div>
  </div>
  
  <div class='grid-2'>
    <div class='button'>A</div>
    <div class='button'>B</div>
    <div class='button'>C</div>
    <div class='button'>D</div>
  </div>
</html>

推荐答案

我认为这两点代码是错误的:

I think the code is wrong in these two points:

  • 常量键= document.getElementsByClassName('keys');->选择器应为键"
  • var元素= document.getElementsByClassName("grid-2");->结果是一个列表(DomTokenList),因此您应该采用第一个元素(var element = document.getElementsByClassName("grid-2")[0];)

这篇关于如何使用getElementsByClassName()添加两个网格并一个接一个地显示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆