gpt4 book ai didi

javascript - 我如何让多个类来监听 Javascript 中的点击事件?

转载 作者:太空宇宙 更新时间:2023-11-03 20:25:56 24 4
gpt4 key购买 nike

我有多个卡片,我想在每次点击时通过 3D 转换单独旋转(不是同时)。但是,我似乎只能翻转第一个,而不能翻转后续的。

var card = document.querySelector('.card');
card.addEventListener( 'click', function() {
card.classList.toggle('is-flipped');
});
body { font-family: sans-serif; }

.scene {
width: 200px;
height: 260px;
border: 1px solid #CCC;
margin: 40px 0;
perspective: 600px;
}

.card {
width: 100%;
height: 100%;
transition: transform 1s;
transform-style: preserve-3d;
cursor: pointer;
position: relative;
}

.card.is-flipped {
transform: rotateY(180deg);
}

.card__face {
position: absolute;
width: 100%;
height: 100%;
line-height: 260px;
color: white;
text-align: center;
font-weight: bold;
font-size: 40px;
backface-visibility: hidden;
}

.card__face--front {
background: red;
}

.card__face--back {
background: blue;
transform: rotateY(180deg);
}
<div class="scene">
<div class="card">
<div class="card__face card__face--front">front</div>
<div class="card__face card__face--back">back</div>
</div>
</div>
<div class="scene">
<div class="card">
<div class="card__face card__face--front">front</div>
<div class="card__face card__face--back">back</div>
</div>
</div>

我尝试将整个东西包装到 class="wrapper"和以下代码中,但仍然没有用:

var x = document.getElementsByClassName("wrapper").querySelectorAll(".scene");  
x.addEventListener( 'click', function() {
x.classList.toggle('is-flipped');

最佳答案

您正在使用 document.querySelector(),它只返回类为 card 的第一个元素。你应该使用 Document.querySelectorAll()然后 forEach() .在循环中添加事件监听器。

var cards = document.querySelectorAll('.card');
Array.from(cards).forEach(card => {
card.addEventListener( 'click', function() {
card.classList.toggle('is-flipped');
});
})
body { font-family: sans-serif; }

.scene {
width: 200px;
height: 260px;
border: 1px solid #CCC;
margin: 40px 0;
perspective: 600px;
}

.card {
width: 100%;
height: 100%;
transition: transform 1s;
transform-style: preserve-3d;
cursor: pointer;
position: relative;
}

.card.is-flipped {
transform: rotateY(180deg);
}

.card__face {
position: absolute;
width: 100%;
height: 100%;
line-height: 260px;
color: white;
text-align: center;
font-weight: bold;
font-size: 40px;
backface-visibility: hidden;
}

.card__face--front {
background: red;
}

.card__face--back {
background: blue;
transform: rotateY(180deg);
}
<div class="scene">
<div class="card">
<div class="card__face card__face--front">front</div>
<div class="card__face card__face--back">back</div>
</div>
</div>
<div class="scene">
<div class="card">
<div class="card__face card__face--front">front</div>
<div class="card__face card__face--back">back</div>
</div>
</div>

关于javascript - 我如何让多个类来监听 Javascript 中的点击事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54676647/

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