以下是一个简单的相册功能的实现示例:
<!DOCTYPE html>
<html>
<head>
<title>相册</title>
<style>
.gallery {
display: flex;
flex-wrap: wrap;
}
.gallery img {
width: 150px;
height: 150px;
object-fit: cover;
margin: 5px;
cursor: pointer;
}
.modal {
display: none;
position: fixed;
z-index: 1;
padding-top: 100px;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgba(0,0,0,0.9);
}
.modal-content {
margin: auto;
display: block;
width: 80%;
max-width: 700px;
}
.modal-content img {
width: 100%;
height: auto;
}
.close {
color: #fff;
position: absolute;
top: 15px;
right: 35px;
font-size: 40px;
font-weight: bold;
opacity: 0.7;
cursor: pointer;
}
.close:hover,
.close:focus {
color: #fff;
text-decoration: none;
cursor: pointer;
opacity: 1;
}
</style>
</head>
<body>
<div class="gallery">
<img src="image1.jpg" alt="Image 1">
<img src="image2.jpg" alt="Image 2">
<img src="image3.jpg" alt="Image 3">
<img src="image4.jpg" alt="Image 4">
</div>
<div id="myModal" class="modal">
<span class="close">×</span>
<img class="modal-content" id="modalImage">
</div>
<script>
// 获取所有图片元素
var images = document.querySelectorAll('.gallery img');
// 获取模态框
var modal = document.getElementById('myModal');
// 获取模态框中的图片
var modalImage = document.getElementById('modalImage');
// 获取关闭按钮
var closeButton = document.getElementsByClassName('close')[0];
// 点击图片时显示模态框
images.forEach(function(image) {
image.addEventListener('click', function() {
modal.style.display = 'block';
modalImage.src = this.src;
});
});
// 点击关闭按钮或模态框之外的区域时关闭模态框
window.addEventListener('click', function(event) {
if (event.target == modal || event.target == closeButton) {
modal.style.display = 'none';
}
});
</script>
</body>
</html>
这个示例实现了一个简单的相册功能,通过点击图片,可以在模态框中显示大图。用户可以在模态框中点击关闭按钮或模态框之外的区域来关闭模态框。