我試圖通過點擊一個按鈕來顯示一個圖像及其描述。 但是,我想在每次單擊另一個按鈕時關閉前一個框。有人能幫我嗎?
我已經嘗試了幾種方法,但是不能解決它。
我相信這就是你想要達到的目標。每個圖像都包含在一個具有唯一id的div元素和CSS類image-container中,默認情況下使用CSS隱藏描述。單擊按鈕會將該按鈕的id切換為活動狀態,并顯示相應的照片和描述。
<!DOCTYPE html>
<html>
<head>
<title>Image Description</title>
<style>
.image-container {
display: none;
text-align: center;
}
.image-container.active {
display: block;
}
.description {
display: none;
}
.description.active {
display: block;
}
</style>
</head>
<body>
<button onclick="toggleImageDescription('image1')">Show Image 1</button>
<button onclick="toggleImageDescription('image2')">Show Image 2</button>
<button onclick="toggleImageDescription('image3')">Show Image 3</button>
<div id="image1" class="image-container">
<img src="image1.jpg" alt="Image 1">
<div class="description">Description for Image 1</div>
</div>
<div id="image2" class="image-container">
<img src="image2.jpg" alt="Image 2">
<div class="description">Description for Image 2</div>
</div>
<div id="image3" class="image-container">
<img src="image3.jpg" alt="Image 3">
<div class="description">Description for Image 3</div>
</div>
<script>
function toggleImageDescription(imageId) {
const imageContainer = document.getElementById(imageId);
const description = imageContainer.querySelector(".description");
// Close previously opened image containers
const activeContainers = document.querySelectorAll(".image-container.active");
activeContainers.forEach(container => {
container.classList.remove("active");
});
// Toggle visibility of the clicked image container and description
imageContainer.classList.toggle("active");
description.classList.toggle("active");
}
</script>
</body>
</html>