js+css+html实现图片预览

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>lunbo</title>
<style>
    .img {
        width: 200px;
        height: 200px;
        border: 1px solid black;
        object-fit: contain;
    }

    .preview {
        cursor: pointer;
    }

    .preview-container {
        background-color: rgba(0,0,0,0.6);
        position: fixed;
        margin: auto;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        cursor: pointer;

        display: flex;
        justify-content: center;
        align-items: center;
    }

    .preview-container .image {
        max-width: 90vw;
        max-height: 90vh;
        object-fit: contain;
    }
</style>
</head>
<body>
<img src="https://3yya.com/%E8%AF%B8%E8%91%9B%E4%BA%AE.jpg" alt="" class="img preview">
<img src="https://3yya.com/jinji.jpg" alt="" class="img preview">
<img src="https://3yya.com/jinji-2.jpg" alt="" class="img preview">
<script>//head内的js会阻塞页面的传输和页面的渲染,因此放在body的尾部。外联的js放在head中。
    for (const img of document.querySelectorAll(".preview")) {//遍历原来的小图片数组
        img.onclick = function () {//点击小图片后调用本函数,创建大图片容器div,然后创建大图片追加到div中,div再追加到body中。
            const container = document.createElement("div");
            container.classList.add("preview-container")
            container.onclick = function () {
                container.remove()
            }

            const innerImg = document.createElement("img")//创建大图片元素,参数就是img标签名。
            innerImg.classList.add("image")
            innerImg.src = img.src
            container.onwheel = function (event) {//滚动条动作时调用函数,参数为event事件,deltaY>0就是向下。
                if (event.deltaY < 0) {
                    innerImg.style.width = `${innerImg.clientWidth * 1.2}px`
                    innerImg.style.height = `${innerImg.clientHeight * 1.2}px`
                } else if (event.deltaY > 0) {
                    innerImg.style.width = `${innerImg.clientWidth * 0.8}px`
                    innerImg.style.height = `${innerImg.clientHeight * 0.8}px`
                }
            }
            container.append(innerImg)
            document.body.append(container)
        }
    }
</script>
</body>
</html>
经验分享 程序员 微信小程序 职场和发展