为什么在我的 HTML/CSS/JavaScript 设置中单击单张卡片时会同时打开多张卡片?

问题描述 投票:0回答:1

首先 - 这里是菜鸟编码员,经验很少。我有一个包含多张卡片的网页,每张卡片代表一个博物馆展览。单击卡片后,我只希望该特定卡片展开并显示附加信息,而其他卡片保持关闭状态。但是,我遇到一个问题,单击一张卡会同时打开该卡和另一张卡,而不在非活动卡上显示文本。

HTML:

<div id="museum-container">
  <!-- Museum 1: Harmony Through Time -->
  <div class="museum-card" onclick="toggleMuseum(this)">
    <img src="music_museum.jpg" alt="Harmony Through Time" class="museum-image">
    <div class="museum-name">harmony through time</div>
    <div class="museum-description">Explore the evolution of music through the ages.</div>
    <button class="start-button" onclick="startMuseum('harmony through time')">Start</button>
  </div>

  <!-- Museum 2: Time Capsule -->
  <div class="museum-card" onclick="toggleMuseum(this)">
    <img src="time_capsule.jpg" alt="time capsule" class="museum-image">
    <div class="museum-name">time capsule</div>
    <div class="museum-description">Embark on a journey through historical artifacts and moments.</div>
    <button class="start-button" onclick="startMuseum('time capsule')">Start</button>
  </div>
</div>

JavaScript:

function toggleMuseum(card) {
    var isActive = card.classList.contains('active');
  
    // Remove active class from all cards
    document.querySelectorAll('.museum-card').forEach(function (element) {
      element.classList.remove('active');
    });
  
    // Toggle active class only on the clicked card
    if (!isActive) {
      card.classList.add('active');
    }
}

CSS:

.museum-card.active .museum-description,
.museum-card.active .start-button {
  display: block;
}

.active {
  background-color:rgb(177, 134, 70);
}

我尝试过使用警报功能来查找错误所在,但无论我把它放在哪里,它都不会出现。

javascript html css event-handling dom-manipulation
1个回答
0
投票

为了防止这种情况,您可以在toggleMuseum函数中使用event.stopPropagation()来停止事件传播。以下是修改 JavaScript 代码的方法:

函数toggleMuseum(卡片,事件){ event.stopPropagation(); // 停止事件传播

var isActive = card.classList.contains('active');

// Remove active class from all cards
document.querySelectorAll('.museum-card').forEach(function (element) {
    element.classList.remove('active');
});

// Toggle active class only on the clicked card
if (!isActive) {
    card.classList.add('active');
}

}

© www.soinside.com 2019 - 2024. All rights reserved.