一尘不染

多个div在同一页面中翻转

javascript

如何调整以下代码以使多个 div 可以在同一页面上进行此翻转?

Js 仅适用于第一个条目但我希望能够在同一页面上翻转多个 div。

var card = document.querySelector('.card');
card.addEventListener('click', function() {
  card.classList.toggle('is-flipped');
});
.flip-box {
  background-color: transparent;
  width: 300px;
  height: 200px;
  border: 1px solid #f1f1f1;
}

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

.flip-box-front,
.flip-box-back {
  position: absolute;
  width: 100%;
  height: 100%;
  -webkit-backface-visibility: hidden;
  backface-visibility: hidden;
}

.flip-box-front {
  background-color: #bbb;
  color: black;
}

.flip-box-back {
  background-color: #333;
  color: white;
  transform: rotateY(180deg);
}

.card.is-flipped {
  transform: rotateY(180deg);
}
<div class="flip-box">
  <div class="card">
    <div class="flip-box-front">
      <h2>Front Side</h2>
      <p> click to fillp </p>
      <p> click to fillp </p>
      <p> click to fillp </p>
    </div>
    <div class="flip-box-back">
      <h2>Back Side</h2>
      <p> click to fillp </p>
      <p> click to fillp </p>
      <p> click to fillp </p>
    </div>
  </div>
</div>

阅读 91

收藏
2022-07-26

共1个答案

一尘不染

首先,我querySelector改为querySelectorAll. 然后,我遍历页面上的所有卡片并附加单击事件处理程序,就像您最初所做的那样。

var cards = document.querySelectorAll('.card');

cards.forEach(card => {
  card.addEventListener('click', function() {
    card.classList.toggle('is-flipped');
  });
})
.flip-box {
  background-color: transparent;
  width: 300px;
  height: 200px;
  border: 1px solid #f1f1f1;
}

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

.flip-box-front,
.flip-box-back {
  position: absolute;
  width: 100%;
  height: 100%;
  -webkit-backface-visibility: hidden;
  backface-visibility: hidden;
}

.flip-box-front {
  background-color: #bbb;
  color: black;
}

.flip-box-back {
  background-color: #333;
  color: white;
  transform: rotateY(180deg);
}

.card.is-flipped {
  transform: rotateY(180deg);
}
<div class="flip-box">
  <div class="card">
    <div class="flip-box-front">
      <h2>Front Side</h2>
      <p> click to fillp </p>
      <p> click to fillp </p>
      <p> click to fillp </p>
    </div>

    <div class="flip-box-back">
      <h2>Back Side</h2>
      <p> click to fillp </p>
      <p> click to fillp </p>
      <p> click to fillp </p>

    </div>
  </div>

  <div class="card">
    <div class="flip-box-front">
      <h2>Front Side</h2>
      <p> click to fillp </p>
      <p> click to fillp </p>
      <p> click to fillp </p>
    </div>

    <div class="flip-box-back">
      <h2>Back Side</h2>
      <p> click to fillp </p>
      <p> click to fillp </p>
      <p> click to fillp </p>

    </div>
  </div>
</div>
2022-07-26