我有一张点击后反转的卡片,我使用的是jQuery,但我需要在纯JavaScript上实现此效果,我搜索了另一个问题,但没有找到准确的解决方案,这是我的html部分:
<div class="card">
<div class="front"><img src="1.jpg" alt=""></div>
<div class="back"><img src="2.jpg" alt=""></div>
</div>
和CSS:
.card {
width: 200px;
height: 300px;
position: relative;
perspective: 1000px;
cursor: pointer;
}
.front, .back {
width: 100%;
height: 100%;
position: absolute;
display: flex;
justify-content: center;
align-items: center;
transition: 1s;
backface-visibility: hidden;
border-radius: 10px;
}
.front {
transform: rotateY(360deg);
}
.back {
transform: rotateY(180deg);
}
最后是jquery部分:
$('.card').click( function(){
$('.front, .back').toggleClass('back front');
});
我尝试了不同的纯js解决方案,但仅实现了前后切换,而我的目标是同时进行前后切换,反之亦然。 谢谢您的帮助。
答案 0 :(得分:2)
var cards = document.querySelectorAll('.card')
Array.from(cards).forEach(function(card) {
card.addEventListener('click', function() {
Array.from(card.querySelectorAll('.back, .front')).forEach(function(el) {
['back', 'front'].forEach(function(s) {
el.classList.toggle(s)
});
});
});
});
.card {
width: 200px;
height: 300px;
position: relative;
perspective: 1000px;
cursor: pointer;
}
.front,
.back {
width: 100%;
height: 100%;
position: absolute;
display: flex;
justify-content: center;
align-items: center;
transition: 1s;
backface-visibility: hidden;
border-radius: 10px;
}
.front {
transform: rotateY(360deg);
}
.back {
transform: rotateY(180deg);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="card">
<div class="front">Front</div>
<div class="back">Back</div>
</div>