console
let imgLayer=document.querySelector("#img-layer");
if(!imgLayer){
imgLayer=document.createElement("div");
imgLayer.setAttribute("id","img-layer");
document.documentElement.appendChild(imgLayer);
}
// 浏览窗口
const openLayer=function(event){
const target=event.target
// clone一份
cloneImg=target.cloneNode(true);
// 隐藏原图
target.style.visibility="hidden";
target.style.opacity=0;
// 加个状态属性,方便查找
target.setAttribute("layer-status","yes");
// 加载大图
imgLayer.style.visibility="visible"
imgLayer.innerHTML="";
cloneImg.visibility="visible";
cloneImg.opacity=1;
imgLayer.appendChild(cloneImg);
// 监听滚动事件,关闭
document.addEventListener("scroll",closeLayer);
}
// 关闭窗口
const closeLayer=function(e){
const img=document.querySelector(".post-content img[layer-status='yes']");
if(!img){
return false;
}
img.style.visibility="visible";
img.style.opacity=1;
img.setAttribute("layer-status","no");
imgLayer.style.visibility="hidden"
imgLayer.innerHTML="";
document.removeEventListener("scroll",closeLayer);
}
// 监听层关闭
imgLayer.addEventListener("click",closeLayer);
// 监听图片,打开
const imgs=document.querySelectorAll(".post-content img");
imgs && imgs.forEach(function(img){
img.addEventListener("click",openLayer);
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<article class="post-content">
<span>方形的</span>
<img src="https://img.hi-arkin.com/blog/pic/1001.jpeg-md.webp" alt="方形的" srcset="">
<span>竖状的</span>
<img src="https://img.hi-arkin.com/blog/pic/1003.jpeg-md.webp" alt="竖状的" srcset="">
<span>很宽的</span>
<img src="https://img.hi-arkin.com/blog/pic/1004.jpeg-md.webp" alt="很宽" srcset="">
</article>
</body>
</html>
#img-layer{
position: fixed;
z-index: 999;
inset: 0px;
cursor: zoom-out;
background: rgba(18, 18, 18, 0.45);
will-change: opacity;
visibility:hidden;
width: 100vw;
height:100vh;
display: flex;
align-items: center;
justify-content: center;
}
#img-layer > img{
inset: 0px;
width: 100%;
height: 100%;
object-fit: contain;
background: content-box;
}
@keyframes animation-zoom {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
.post-content img{
cursor: zoom-in;
display: inline-block;
background-color: transparent;
animation: animation-zoom 0.5s ease-in;
max-height: 200px;
}