在上一篇文章中,讲到了单张图片,如何实现点击放大查看,很多读者询问了关于如何在多张图片中实现相同的效果,多张图片需要注意的是,不能给每张图片添加相同的id,因为id是唯一的,所以可以用类名代替
,并为每张图片添加事件监听器。
效果展示

;
}
.modal-content {
margin: auto;
display: block;
width: 80%;
max-width: 700px;
}
.modal-content {
-webkit-animation-name: zoom;
-webkit-animation-duration: 0.6s;
animation-name: zoom;
animation-duration: 0.6s;
}
@-webkit-keyframes zoom {
from {
-webkit-transform: scale(0)
}
to {
-webkit-transform: scale(1)
}
}
@keyframes zoom {
from {
transform: scale(0)
}
to {
transform: scale(1)
}
}
/* 关闭按钮 */
.close {
position: absolute;
top: 15px;
right: 35px;
color: #f1f1f1;
font-size: 40px;
font-weight: bold;
transition: 0.3s;
}
.close:hover,
.close:focus {
color: #bbb;
text-decoration: none;
cursor: pointer;
}
三、JS 代码
js
var modal = document.getElementById("modal");
var modalImg = document.getElementById("modalImage");
var images = document.querySelectorAll(".zoomable");
// 遍历为每个图片元素添加事件监听器
images.forEach(function (image) {
image.addEventListener("click", function () {
modal.style.display = "block";
modalImg.src = this.src;
});
});
var span = document.querySelector(".close");
span.addEventListener("click", function () {
modal.style.display = "none";
});
modal.addEventListener("click", function (event) {
if (event.target == modal) {
modal.style.display = "none";
}
});
这样就可以实现在有多张图片的情况下,也能正常实现放大查看并关闭