以下是一個簡單的相冊功能的實現示例:
<!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>
這個示例實現了一個簡單的相冊功能,通過點擊圖片,可以在模態框中顯示大圖。用戶可以在模態框中點擊關閉按鈕或模態框之外的區域來關閉模態框。