使

使用 JavaScript 创建图像模式!

2025-06-10

使用 JavaScript 创建图像模式!

嗨,大家好!

在本教程中,我们将使用 JavaScript 创建一个弹出式图片模态窗口。其基本思路是,当用户点击图片时,模态窗口会打开一个更大的版本。这种做法在灯箱图库和其他图片库中很常见。

查看详细的 javascript 图库教程,其中还包括图像导航。

Javascript 模态画廊


创建图像网格

首先,我们将使用 CSS 网格创建一个图片网格。你也可以使用一张图片创建一个模态框,但多张图片更符合实际,而且也可以用于灯箱部分。

HTML 标记

本教程可以使用任何图像。HTML 标记非常简单:



<!DOCTYPE html>
<html lang="en">

<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script async src="https://kit.fontawesome.com/6cc05e1e8e.js" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="./style.css">
    <meta charset="UTF-8" />
</head>

<body>
    <div class="main">
        <h1>Gallery</h1>
        <div class="gallery">
            <div class="gallery__item">
                <img src="./img/1.jpg" />
            </div>
            <div class="gallery__item">
                <img src="./img/2.jpg" />
            </div>
            <div class="gallery__item">
                <img src="./img/3.jpg" />
            </div>
            <div class="gallery__item">
                <img src="./img/4.jpg" />
            </div>
            <div class="gallery__item">
                <img src="./img/5.jpg" />
            </div>
            <div class="gallery__item">
                <img src="./img/6.jpg" />
            </div>
            <div class="gallery__item">
                <img src="./img/7.jpg" />
            </div>
            <div class="gallery__item">
                <img src="./img/8.jpg" />
            </div>
        </div>
    </div>
</body>

</html>


Enter fullscreen mode Exit fullscreen mode

你可能会注意到一些细节。首先,我导入了 Font Awesome 作为关闭按钮的图标。我还链接了 style.css,其中包含我们的 CSS。我们有 8 张图片,每张图片都放在一个名为 的 div 中gallery__item

画廊风格

CSS 代码相当直观。我们在主容器上使用 flex box 来使所有内容在垂直和水平方向上居中。接下来,我们使用 CSS grid 创建一个 4 列 2 行的图像网格。



* {
    padding: 0;
    margin: 0;
    box-sizing: border-box;
}

.main {
    width: 100%;
    flex-direction: column;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 20px 0px 60px 0px;
}

h1 {
    margin: 10px 0px 30px 0px;
    font-family: cursive;
    color: rgb(0, 6, 90);
    font-size: 50px;
}

.gallery {
    display: grid;
    width: 90%;
    grid-template-columns: repeat(4, 1fr);
    grid-gap: 10px;
}

.gallery__item {
    cursor: pointer;
    overflow: hidden;
    border-radius: 4px;
}

.gallery__item img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    transition: 0.3s ease-in-out;
}

.gallery__item img:hover {
    transform: scale(1.1);
}

@media (max-width: 950px) {
    .gallery {
        grid-template-columns: repeat(2, 1fr);
    }
}

@media (max-width: 550px) {
    .gallery {
        grid-template-columns: repeat(1, 1fr);
    }
}



Enter fullscreen mode Exit fullscreen mode

您的画廊现在应该是这样的:
浏览器视图

JavaScript

接下来我们需要创建点击图片时打开图片的 JS 代码。首先,导入脚本:



<script defer src="./script.js"></script>


Enter fullscreen mode Exit fullscreen mode

获取图像源

现在,我们需要创建一个函数,当点击图片时,它会返回图片的 src 值。为此,我们将对forEach所有图片运行一个循环,并将图片url存储在变量imgSrce.target.src中。



const images = document.querySelectorAll(".gallery__item img");
let imgSrc;
// get images src onclick
images.forEach((img) => {
    img.addEventListener("click", (e) => {
        imgSrc = e.target.src;
    });
});


Enter fullscreen mode Exit fullscreen mode

创建模态框和图像

现在我们将创建一个函数,每次点击图片时都会创建一个空的模态框。这里我们只是创建了一个带有modal类的 div 。

接下来,我们需要创建图片并将其添加到模态框中。图片的 src 是我们之前存储在 imgSrc 变量中的值。我们将使用参数访问它。



//creating the modal
let imgModal = (src) => {
    const modal = document.createElement("div");
    modal.setAttribute("class", "modal");
    //add the modal to the main section or the parent element
    document.querySelector(".main").append(modal);
    //adding image to modal
    const newImage = document.createElement("img");
    newImage.setAttribute("src", src);
    modal.append(newImage)
};


Enter fullscreen mode Exit fullscreen mode

为了设置模态框和图像的样式,我们将使用 .modal 类并将以下代码添加到 style.css。



/*Image modal*/

.modal {
    width: 100%;
    height: 100%;
    position: fixed;
    top: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: rgba(0, 0, 0, 0.733);
    margin-top: -1px;
    animation: zoom 0.3s ease-in-out;
}

@keyframes zoom {
    from {
        transform: scale(0);
    }
    to {
        transform: scale(1);
    }
}
.modal img {
    width: 50%;
    object-fit: cover;
}


Enter fullscreen mode Exit fullscreen mode

创建关闭按钮

最后,我们需要创建一个关闭按钮来关闭模态框。我们将使用 Font Awesome 创建关闭图标,并创建一个简单的函数来移除模态框。



//creating the close button
const closeBtn = document.createElement("i");
closeBtn.setAttribute("class", "fas fa-times closeBtn");
//close function
closeBtn.onclick = () => {
    modal.remove();
};
modal.append(newImage, closeBtn);


Enter fullscreen mode Exit fullscreen mode

还可以设置图标的样式:



.closeBtn {
    color: rgba(255, 255, 255, 0.87);
    font-size: 25px;
    position: absolute;
    top: 0;
    right: 0;
    margin: 20px;
    cursor: pointer;
    transition: 0.2s ease-in-out;
}

.closeBtn:hover {
    color: rgb(255, 255, 255);
}


Enter fullscreen mode Exit fullscreen mode

完整的JS代码

这是完整的 javascript 代码。



const images = document.querySelectorAll(".gallery__item img");
let imgSrc;
// get images src onclick
images.forEach((img) => {
    img.addEventListener("click", (e) => {
        imgSrc = e.target.src;
        //run modal function
        imgModal(imgSrc);
    });
});
//creating the modal
let imgModal = (src) => {
    const modal = document.createElement("div");
    modal.setAttribute("class", "modal");
    //add the modal to the main section or the parent element
    document.querySelector(".main").append(modal);
    //adding image to modal
    const newImage = document.createElement("img");
    newImage.setAttribute("src", src);
    //creating the close button
    const closeBtn = document.createElement("i");
    closeBtn.setAttribute("class", "fas fa-times closeBtn");
    //close function
    closeBtn.onclick = () => {
        modal.remove();
    };
    modal.append(newImage, closeBtn);
};



Enter fullscreen mode Exit fullscreen mode

您的图库现在应该像这样运行:

输出

你已经完成了!


感谢大家阅读这篇文章!
查看完整的 JS 画廊教程:

Javascript 模态画廊

如果您喜欢我的作品,您可以请我喝杯咖啡并分享您的想法🎉☕
给我买杯咖啡

下次再见!
干杯!🎉

鏂囩珷鏉ユ簮锛�https://dev.to/salehmubahar/create-an-image-modal-with-javascript-2lf3
PREV
介绍 NEXT.js 的替代方案
NEXT
React 中的 3 个高级 Framer 运动效果