<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
/* image-gallery.css */
.thumbnail {
width: 100px;
height: 100px;
cursor: pointer;
}
.overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.8);
display: none;
justify-content: center;
align-items: center;
z-index: 9999;
}
.original-image {
max-width: 90%;
max-height: 90%;
}
.close-overlay {
position: absolute;
top: 20px;
right: 30px;
font-size: 30px;
color: white;
cursor: pointer;
}
</style>
<body>
<div id="imageGallery">
<img src="example.jpg" alt="图片1" />
<img src="2.png" alt="图片2" />
<img src="3.png" alt="图片3" />
<img src="4.png" alt="图片4" />
</div>
<script src="image-gallery.js"></script>
</body>
<script>
function ImageGallery(containerId) {
const container = document.getElementById(containerId);
if (!container) {
console.error(`无法找到ID为 "${containerId}" 的容器`);
return;
}
// 创建遮罩层
const overlay = document.createElement('div');
overlay.className = 'overlay';
const originalImage = document.createElement('img');
originalImage.className = 'original-image';
const closeOverlay = document.createElement('span');
closeOverlay.className = 'close-overlay';
closeOverlay.textContent = '×';
overlay.appendChild(originalImage);
overlay.appendChild(closeOverlay);
document.body.appendChild(overlay);
// 获取容器内的所有图片
const images = container.querySelectorAll('img');
images.forEach((img) => {
img.classList.add('thumbnail');
// 等待图片加载完成,获取原始尺寸
img.onload = function () {
const originalWidth = this.naturalWidth;
const originalHeight = this.naturalHeight;
// 将原始尺寸存储到数据属性中
img.dataset.originalWidth = originalWidth;
img.dataset.originalHeight = originalHeight;
// 设置缩略图固定大小
img.style.width = '150px';
img.style.height = '150px';
};
// 点击缩略图时显示遮罩层
img.addEventListener('click', function () {
const originalWidth = this.dataset.originalWidth;
const originalHeight = this.dataset.originalHeight;
// 更新遮罩层中的原图尺寸和来源
originalImage.src = this.src;
originalImage.style.width = `${originalWidth}px`;
originalImage.style.height = `${originalHeight}px`;
// 显示遮罩层
overlay.style.display = 'flex';
});
});
// 关闭遮罩层
closeOverlay.addEventListener('click', function () {
overlay.style.display = 'none';
});
}
// 使用示例
document.addEventListener("DOMContentLoaded", function () {
new ImageGallery('imageGallery'); // 传入目标容器的ID
});
</script>
</html>
图片遮罩层,点击图片看大图
最新推荐文章于 2025-05-18 03:42:29 发布