使用forEach更改多个图像

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

所以我创建了一张图片幻灯片,并且有一张显示图片作为背景图像。我使用 forEach 循环浏览图片,以便单击其中任何一个图片时,单击的图片将显示在显示 div 上。 但我似乎无法让它们显示

我只是想知道如何让图片显示

javascript image foreach upload display
1个回答
0
投票

要使用JavaScript和

forEach
更改显示div点击不同图片时的背景图像,您可以按照以下步骤操作:

<!DOCTYPE html>
<html>
<head>
    <style>
    /* Style for the display div */
    #display {
        width: 400px; /* Set the width and height to your desired values */
        height: 300px;
        background-size: cover; /* Ensure the background image covers the div */
    }
    
    /* Style for the image list */
    #imageList {
        display: flex; /* Display images horizontally */
        justify-content: space-around; /* Space them evenly */
        margin-top: 20px; /* Add some top margin to space them from the display div */
    }
    
    #imageList img {
        cursor: pointer; /* Change cursor to a pointer when hovering over images */
        width: 100px; /* Set the width of each image */
        height: 100px; /* Set the height of each image */
        border: 2px solid #000; /* Add a border for a visual effect */
    }
  
    </style>
</head>
<body>
    <div id="display"></div>
    <div id="imageList">
        <img src="image1.jpg" alt="Image 1">
        <img src="image2.jpg" alt="Image 2">
        <img src="image3.jpg" alt="Image 3">
    </div>
    <script>
        // Get references to the display div and the image list
        const displayDiv = document.getElementById("display");
        const imageList = document.getElementById("imageList");

        // Get all the images in the image list and convert them to an array
        const images = Array.from(imageList.getElementsByTagName("img"));

        // Set the background image of the display div to the first image when the page loads
        const firstImage = images[0];
        const firstImageURL = firstImage.getAttribute("src");
        displayDiv.style.backgroundImage = `url(${firstImageURL})`;

        // Use forEach to add a click event listener to each image
        images.forEach((image, index) => {
            image.addEventListener("click", () => {
                // Get the source (URL) of the clicked image
                const imageURL = image.getAttribute("src");

                // Set the background image of the display div to the clicked image
                displayDiv.style.backgroundImage = `url(${imageURL})`;
            });
        });

    </script>
</body>
</html>
© www.soinside.com 2019 - 2024. All rights reserved.