如何在JavaScript上单击按钮时关闭上一个元素

bnlyeluc  于 2023-05-16  发布在  Java
关注(0)|答案(1)|浏览(158)

我正试图通过单击按钮来显示图像及其说明。但是,我想在每次单击另一个按钮时关闭前一个框。有人能帮帮我吗
我试过几种方法,但都不明白。

mzillmmw

mzillmmw1#

我相信这就是你想达到的目的。每个图像都包含在一个具有唯一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>

相关问题