问题
- I Have Tried to add grid-2 when we press a key, but it's not working as I expected.
- When it is displaying grid-2 I want the grid to disappear (I don't know how to do).
(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.
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>
回答1:
I think the code is wrong in these two points:
- const key = document.getElementsByClassName('keys'); --> The selector should be 'key'
- var element = document.getElementsByClassName("grid-2"); --> The result is a list (DomTokenList), so you should take the first element (var element = document.getElementsByClassName("grid-2")[0];)
来源:https://stackoverflow.com/questions/63285169/how-to-use-getelementsbyclassname-for-adding-both-grids-and-display-one-after