gpt4 book ai didi

Javascript - 如何创建多个使用 onclick() 翻转的翻转卡?

转载 作者:行者123 更新时间:2023-12-04 08:21:18 24 4
gpt4 key购买 nike

我在我正在开发的纸牌游戏中添加多张翻牌时遇到问题。
我的代码适用于一张卡片,但由于我使用 getElementById 使其工作,因此当我添加更多卡片时它停止工作,因为 ID 是唯一的。任何的想法?我想用 vanilla javascript 来实现这一点。
HTML:

<body>
<div class="flexbox">
<div class="flip-card" style="margin: 100px 0 0 100px">
<div class="flip-card-inner">
<div class="flip-card-front" id="front" onclick="flip()">
<img
src="/images/strawman.png"
alt="Avatar"
style="width:100px;height:auto"
/>
<h2>The strawman</h2>
</div>
<div class="flip-card-back" id="back" onclick="flip()">
<div style="vertical-align: middle;">
<h3>The strawman</h3>
<p>
Transforming your opponent's argument into a caricature that you
can more easily attack
</p>
</div>
</div>
</div>
</div>
<div class="flip-card" style="margin: 100px 0 0 100px">
<div class="flip-card-inner">
<div class="flip-card-front" id="front" onclick="flip()">
<img
src="/images/strawman.png"
alt="Avatar"
style="width:100px;height:auto"
/>
<h2>The strawman</h2>
</div>
<div class="flip-card-back" id="back" onclick="flip()">
<div style="vertical-align: middle;">
<h3>The strawman</h3>
<p>
Transforming your opponent's argument into a caricature that you
can more easily attack
</p>
</div>
</div>
</div>
</div>
</div>

Javascript :
 <script>
let toggle = true;

function flip() {
if (toggle == true) {
document.getElementById("front").style.transform = "rotateY(180deg)";
document.getElementById("back").style.transform = "rotateY(0deg)";
toggle = !toggle;
console.log(toggle);
} else {
document.getElementById("front").style.transform = "rotateY(0deg)";
document.getElementById("back").style.transform = "rotateY(-180deg)";
toggle = !toggle;
console.log(toggle);
}
}
</script>
谢谢您的帮助 :)

最佳答案

第一步是到 avoid inline handlers ,他们有太多的问题,现在不值得使用。使用 addEventListener 附加事件监听器反而。
考虑使用 CSS 类在不同的旋转之间切换,例如:

.flip-card-inner .flip-card-front {
transform: rotateY(180deg);
}
.flip-card-inner .flip-card-back {
transform: rotateY(0deg);
}

.flip-card-inner.flipped .flip-card-front {
transform: rotateY(0deg);
}
.flip-card-inner.flipped .flip-card-back {
transform: rotateY(-180deg);
}
for (const frontOrBack of document.querySelectorAll('.flip-card-inner *')) {
frontOrBack.addEventListener('click', () => {
frontOrBack.parentElement.classList.toggle('flipped');
});
}

关于Javascript - 如何创建多个使用 onclick() 翻转的翻转卡?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65485778/

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