1 回答
TA贡献1818条经验 获得超7个赞
等待 transitionend 可能会导致更多的问题而不是它的价值。我不确定您的浏览器兼容性要求,但如果您可以使用动画,我建议您使用它们:
let images = ['https://adiihd.github.io/rock-paper-scissors-game/img/rock.png', 'https://adiihd.github.io/rock-paper-scissors-game/img/paper.png', 'https://adiihd.github.io/rock-paper-scissors-game/img/scissors.png'];
const buttons = document.querySelectorAll('button');
// we use the .forEach method to iterate through each button
buttons.forEach((button) => {
// and for each one we add a 'click' listener
button.addEventListener('click', async (e) => {
let userImg = document.querySelector(".userimg");
userImg.classList.remove("userimg-animation");
// Force a reflow, see https://css-tricks.com/restart-css-animation/
userImg.offsetWidth;
userImg.classList.add("userimg-animation");
userImg.setAttribute("choice", button.id.toLowerCase());
});
});
.imageHolder {
position: relative;
display: inline-block;
}
.spacerimg {
opacity: 0;
}
.userimg-animation {
width: 100%;
height: 100%;
position: absolute;
animation-name: rockpaperscissors;
animation-duration: 1.2s;
}
.userimg {
background-repeat: no-repeat!important;
}
.userimg[choice="rock"] {
background: url(https://adiihd.github.io/rock-paper-scissors-game/img/rock.png);
}
.userimg[choice="paper"] {
background: url(https://adiihd.github.io/rock-paper-scissors-game/img/paper.png);
}
.userimg[choice="scissors"] {
background: url(https://adiihd.github.io/rock-paper-scissors-game/img/scissors.png);
}
@keyframes rockpaperscissors {
0% {
background: url(https://adiihd.github.io/rock-paper-scissors-game/img/rock.png);
}
33.2% {
background: url(https://adiihd.github.io/rock-paper-scissors-game/img/rock.png);
}
33.3% {
background: url(https://adiihd.github.io/rock-paper-scissors-game/img/paper.png);
}
66.5% {
background: url(https://adiihd.github.io/rock-paper-scissors-game/img/paper.png);
}
66.6% {
background: url(https://adiihd.github.io/rock-paper-scissors-game/img/scissors.png);
}
99.9% {
background: url(https://adiihd.github.io/rock-paper-scissors-game/img/scissors.png);
}
100% {
background: none;
}
}
<div class="imageHolder">
<div class="userimg"></div>
<img class="spacerimg" src="https://adiihd.github.io/rock-paper-scissors-game/img/rock.png">
</div>
<br>
<button id="Rock">Rock</button>
<button id="Paper">Paper</button>
<button id="Scissors">Scissors</button>
注意:我必须编写额外的关键帧以防止背景之间的动画(它们在彼此之间淡出)。但是您可能需要动画,因此如果您删除每个奇数关键帧,您将拥有更少的 CSS 并且它们将在彼此之间进行动画处理。
添加回答
举报