gpt4 book ai didi

javascript - 动画化数组中的 DOM 元素

转载 作者:太空宇宙 更新时间:2023-11-04 05:48:47 24 4
gpt4 key购买 nike

我一直在尝试编写 Simon Says 游戏的代码,到目前为止,除了游戏的动画方面,我已经完成了所有工作。每当代码遍历数组时,它会在第一次进行动画处理,但如果再次出现相同的方 block ,则不会在第二次进行动画处理。

let red = document.querySelector('.red');
let blue = document.querySelector('.blue');
let yellow = document.querySelector('.yellow');
let green = document.querySelector('.green');

let sounds = [red, blue, red, blue];
let i = -1;

let currentInt = setInterval(() => {
if (i < sounds.length - 1) {
i++;
console.log(sounds[i]);
sounds[i].classList.add('selected');

}

}, 1000)
.simonBoard {
display: grid;
grid-template-columns: 1fr 1fr;
background-color: coral;
margin: 0 auto;
margin-top: 100px;
width: 30%;
height: 400px;
}

.red {
background-color: crimson;
border: 3px solid black;
}

.yellow {
background-color: gold;
}

.blue {
background-color: dodgerblue;
border: 3px solid black;
}

.green {
background-color: forestgreen;
}

.selected {
animation-name: selected;
animation-duration: 0.25s;
}

@keyframes selected {
0% {
border: 3px solid black;
}
50% {
border: 20px solid green;
}
100% {
border: 3px solid black;
}
}
<div class="simonBoard">

<div data-id=0 class="btn red"></div>
<div data-id=2 class="btn yellow"></div>
<div data-id=1 class="btn blue"></div>
<div data-id=3 class="btn green"></div>
</div>

最佳答案

添加一个 animationend 事件监听器,并在动画结束时移除 .selected 类(和事件监听器):

let red = document.querySelector('.red');
let blue = document.querySelector('.blue');
let yellow = document.querySelector('.yellow');
let green = document.querySelector('.green');

let sounds = [red, blue, red, blue];
let i = -1;

let currentInt = setInterval(() => {
if (i < sounds.length - 1) {
i++;

sounds[i].classList.add('selected');

const eventListener = () => {
sounds[i].classList.remove('selected');

sounds[i].removeEventListener('animationend', eventListener);
}

sounds[i].addEventListener('animationend', eventListener);
}
}, 1000)
.simonBoard {
display: grid;
grid-template-columns: 1fr 1fr;
background-color: coral;
margin: 0 auto;
width: 30%;
height: 90vh;
}

.red {
background-color: crimson;
}

.yellow {
background-color: gold;
}

.blue {
background-color: dodgerblue;
}

.green {
background-color: forestgreen;
}

.selected {
animation-name: selected;
animation-duration: 0.25s;
}

/** I've change the border to shadow to prevent the element from resizing **/
@keyframes selected {
0% {
box-shadow: inset 0 0 0 3px black;
}
50% {
box-shadow: inset 0 0 0 20px green;
}
100% {
box-shadow: inset 0 0 0 3px black;
}
}
<div class="simonBoard">
<div data-id=0 class="btn red"></div>
<div data-id=2 class="btn yellow"></div>
<div data-id=1 class="btn blue"></div>
<div data-id=3 class="btn green"></div>
</div>

关于javascript - 动画化数组中的 DOM 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58466857/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com