实现效果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/fcb712cc3565f126024fa42011a3df46.png)
H5代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>京东放大镜</title>
</head>
<body>
<div class="box">
<img src="https://img12.360buyimg.com/n1/s450x450_jfs/t1/59022/28/10293/141808/5d78088fEf6e7862d/68836f52ffaaad96.jpg" alt="">
<div class="mask"></div>
<div class="big">
<img src="https://img12.360buyimg.com/n1/s450x450_jfs/t1/59022/28/10293/141808/5d78088fEf6e7862d/68836f52ffaaad96.jpg" alt="" class="bigImg">
</div>
</div>
</body>
</html>
CSS
<style>
* {
padding: 0;
margin: 0;
}
.box {
position: relative;
width: 400px;
height: 400px;
margin: 50px 0 0 100px;
border: 1px solid #000000;
cursor: move;
}
.box img {
width: 100%;
height: 100%;
}
.mask {
display: none;
position: absolute;
width: 300px;
height: 300px;
top: 0px;
left: 0px;
border: 1px solid #ccc;
background: yellow;
opacity: .5;
}
.big {
display: none;
position: absolute;
width: 600px;
height: 600px;
top: -1px;
left: 411px;
border: 1px solid #000000;
overflow: hidden;
}
.big img {
position: absolute;
width: 800px;
height: 800px;
left: 0px;
top: 0px;
}
</style>
JS代码
<script>
window.addEventListener('load', function() {
var box = document.querySelector('.box');
var mask = document.querySelector('.mask');
var big = document.querySelector('.big');
box.addEventListener('mouseover', function(e) {
mask.style.display = 'block';
big.style.display = 'block';
});
box.addEventListener('mouseout', function() {
mask.style.display = 'none';
big.style.display = 'none';
});
box.addEventListener('mousemove', function(e) {
var x = e.pageX - this.offsetLeft - mask.offsetWidth / 2;
var y = e.pageY - this.offsetTop - mask.offsetHeight / 2;
var maskMax = box.offsetWidth - mask.offsetWidth;
if (x <= 0) x = 0;
if (x >= maskMax) x = maskMax;
if (y <= 0) y = 0;
if (y >= maskMax) y = maskMax;
mask.style.left = x + 'px';
mask.style.top = y + 'px';
var bigImg = document.querySelector('.bigImg');
var bigMax = bigImg.offsetWidth - big.offsetWidth;
var boom = bigMax / maskMax;
var bigX = x * boom;
var bigY = y * boom;
bigImg.style.left = -bigX + 'px';
bigImg.style.top = -bigY + 'px';
});
});
</script>