<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
#small {
width: 500px;
height: 500px;
float: left;
position: relative;
margin-left: 200px;
margin-top: 200px;
}
#small img {
width: 500px;
height: 500px;
}
#mask {
width: 150px;
height: 150px;
background: rgba(255, 255, 255, 0.5);
position: absolute;
top: 0;
left: 0;
cursor: move;
display: none;
}
#big {
width: 500px;
height: 500px;
overflow: hidden;
float: left;
margin-left: 40px;
margin-top: 200px;
display: none;
}
#big img {
width: 1500px;
height: 1500px;
}
</style>
</head>
<body>
<div id="small">
<img src="./0.jpg" alt="">
<div id="mask"></div>
</div>
<div id="big">
<img src="./0.jpg" alt="">
</div>
<script src="./jquery-3.4.1.min.js"></script>
<script>
// 鼠标经过小图显示 遮罩和大盒子
$("#small").mouseenter(function () {
$("#mask,#big").show()
}).mouseleave(function () {
$("#mask,#big").hide()
})
$("#small").mousemove(function (e) {
// e.pageX 和e.pageY 鼠标位置
var x = e.pageX - $("#small").offset().left - $("#mask").width() / 2;
var y = e.pageY - $("#small").offset().top - $("#mask").height() / 2;
// 最小限制
x < 0 ? x = 0 : x;
y < 0 ? y = 0 : y;
// 最大限制
x > $("#small").width() - $("#mask").width() ? x = $("#small").width() - $("#mask").width() : x;
y > $("#small").height() - $("#mask").height() ? y = $("#small").height() - $("#mask").height() : y;
$("#mask").css({
left: x + "px",
top: y + "px"
})
// 算出小盒子和大图片的比例
var bilix = $("#big img").width() / $("#small").width();
var blliy = $("#big img").height() / $("#small").height();
// 根据遮罩的top和left 来滚动大盒子的 scrollLeft和scrollTop
$("#big").scrollLeft(x * bilix);
$("#big").scrollTop(y * blliy)
})
</script>
</body>
</html>`在这里插入代码片`
```![默认图片,拿走不送](https://img-blog.csdnimg.cn/20201221220226667.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3hibF8wMDE=,size_16,color_FFFFFF,t_70#pic_center)
JQuery 图片放大镜代码---
于 2020-12-21 22:03:35 首次发布