<section class="game--section">
<div class="game-space">
<div class="box box1 active-box"></div>
<div class="box box2"></div>
<div class="box box3"></div>
<div class="box box4"></div>
<div class="box box5"></div>
<div class="box box6"></div>
</div>
<div class="restart-button">?</div>
</section>
我有一个包含6个子框的div(.Game-space),其中一个是具有绿色背景的(‘.active-Box)类的活动框,
- 所以当我点击活动框时,将它的类(.active-Box)移到下一个给出绿色背景的框,这样它就会一直移到最后一个框.
我也有重新开始按钮,当我点击它时,游戏应该会重新开始,就像活动框类被标记到第一个框一样,从这里它再次转移到下一个类,并通过点击一直到结束框.
但是,在点击重新开始按钮之前,框之间的移动是线性的,逐个移动,但在点击重新启动按钮后,框是被跳过的,而不是在线性移动之间跳过一些框, 为什么?有什么解决办法吗?
'use strict'
const allBox = document.querySelectorAll('.box');
const activeBox = document.querySelector('.active-box')
const restartButton = document.querySelector('.restart-button')
let active_box_index = activeBox_index_function();
slideBox(allBox[active_box_index]);
function slideBox(pass_active_box) {
pass_active_box.addEventListener('click', function() {
allBox[active_box_index].classList.remove('active-box')
allBox[active_box_index + 1].classList.add('active-box')
active_box_index = activeBox_index_function()
slideBox(allBox[active_box_index]);
})
}
console.log(allBox);
// active box index
function activeBox_index_function() {
let index;
allBox.forEach((el, indx) => {
if (el.matches('.active-box')) {
index = indx
};
})
return index;
}
// when restart button clicked
restartButton.addEventListener('click', function() {
allBox[active_box_index].classList.remove('active-box')
allBox[0].classList.add('active-box')
active_box_index = activeBox_index_function()
})
@import url('https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,200;0,300;0,400;0,600;0,700;0,800;0,900;1,800&display=swap');
@import url('https://fonts.cdnfonts.com/css/common-pixel');
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
html {
font-size: 62.5%;
font-family: 'Poppins', sans-serif;
color: black;
}
.game--section {
height: 100vh;
background-color: #252525;
display: flex;
justify-content: center;
align-items: center;
}
.game-space {
width: 80rem;
height: 10rem;
padding: 1rem;
border-radius: 9px;
background-color: #f5f5f5;
display: grid;
grid-template-columns: repeat(6, 1fr);
gap: 1rem;
}
.box {
background-color: tomato;
}
.active-box {
background-color: #099268;
cursor: pointer;
}
.restart-button {
font-size: 3rem;
cursor: pointer;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<section class="game--section">
<div class="game-space">
<div class="box box1 active-box"></div>
<div class="box box2"></div>
<div class="box box3"></div>
<div class="box box4"></div>
<div class="box box5"></div>
<div class="box box6"></div>
</div>
<div class="restart-button">?</div>
</section>
<script src="script.js"></script>
</body>
</html>