foreword
It is very complicated to write about the JQuery enlarged image preview function on the Internet. This article implements it with the least code.
As shown in the figure below, the preview is triggered when the image is clicked (while the mask layer is displayed in the background), and the preview is closed when the outside is clicked.
full source code
JQuery CDN may fail at any time, please replace it yourself if it fails.
Create a new *.html
file , copy the following code with one click and run it.
<!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>JQ图片预览</title>
<!-- JQuery CDN(失效自行更换引入) -->
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<!-- 样式 -->
<style >
.small {
width: 150px;
height: 150px;
}
.big {
width: 100vw;
height: 100vh;
background: rgba(0, 0, 0, .6);
position: fixed;
top: 0;
left: 0;
z-index: 1;
display: none;
}
.big_img {
width: auto;
height: auto;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
z-index: 2;
}
</style>
<!-- END -->
</head>
<body>
<!-- 小图 -->
<img class="small" src="https://img2.baidu.com/it/u=1361506290,4036378790&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=500">
<img class="small" src="https://img1.baidu.com/it/u=3605832793,3252065221&fm=253&fmt=auto&app=120&f=JPEG?w=800&h=1422">
<!-- END -->
<!-- 大图div -->
<div class="big">
<img class="big_img" src="">
</div>
<!-- END -->
<script>
// 小图点击放大
$("img").click(function() {
// 获取当前点击小图的src
let imgSrc = $(this).attr("src");
// 将获取到的src赋值到大图显示区域img的src里
$(".big_img").attr("src", imgSrc);
// 显示大图区域
$(".big").show();
})
// 隐藏大图显示区域
$(".big").click(function() {
$(this).hide();
})
</script>
</body>
</html>