效果展示
HTML 代码
HTML代码比较简单,包含了一个img元素,用显示原有图片,和一个模态框元素div,用于显示放大之后的图片元素,模拟模态框的样式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Zoom</title>
<link rel="stylesheet" href="index.css">
</head>
<body>
<img id="image" src="https://tse3-mm.cn.bing.net/th/id/OIP-C.9Pt31ku3_vc9N5TlSzIQYAHaEK?w=284&h=180&c=7&r=0&o=5&dpr=1.5&pid=1.7" alt="Image" onclick="zoomImage()">
<div id="modal" class="modal" onclick="closeModal()">
<span class="close" onclick="closeModal()">×</span>
<img class="modal-content" id="modalImage">
</div>
<script src="index.js"></script>
</body>
</html>
CSS
CSS样式比较常规,正常模态框的样式:背景颜色稍暗,铺满整页,凸显放大后的图片。这里为模态框添加了动画,当点击图片时,模态框出现不会显得那么生硬
#image {
width: 100%;
max-width: 300px;
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.1);
}
.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;
cursor: pointer;
}
/*兼容性写法, 确保在webkit内核的浏览器能正常使用*/
@-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: burlywood;
font-size: 40px;
font-weight: bold;
transition: 0.3s;
}
.close:hover,
.close:focus {
color: white;
text-decoration: none;
cursor: pointer;
}
JS
JS代码就有两个功能,点击后,然模态框可见,以及模态框的关闭
//显示模态框
function zoomImage() {
var modal = document.getElementById("modal");
var modalImg = document.getElementById("modalImage");
var img = document.getElementById("image");
modal.style.display = "block";
modalImg.src = img.src;
}
//关闭模态框
function closeModal() {
var modal = document.getElementById("modal");
modal.style.display = "none";
}