代码
<!DOCTYPE html>
<html lang="e1n">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
.box {
position: relative;
margin-left: 50px;
}
.yuantu {
position: relative;
width: 400px;
height: 400px;
border: 1px solid green;
}
.mask {
position: absolute;
left: 20px;
top: 20px;
display: none;
width: 200px;
height: 200px;
background-color: rgba(255, 0, 0, 0.5);
}
.enlarge {
position: absolute;
border: 1px solid red;
left: 410px;
top: 0;
width: 400px;
height: 400px;
overflow: hidden;
display: none;
}
.enlarge img {
position: absolute;
width: 800px;
height: 800px;
}
img {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div class="box">
<div class="yuantu">
<img src="./img/1.png" alt="" />
<div class="mask"></div>
</div>
<div class="enlarge"><img src="./img/1.png" alt="" /></div>
</div>
<script>
var yuantu = document.querySelector(".yuantu");
var enlargeImg = document.querySelector(".enlarge img");
var enlarge = document.querySelector(".enlarge");
var mask = document.querySelector(".mask");
yuantu.onmouseenter = function() {
enlarge.style.display = "block";
mask.style.display = "block";
yuantu.onmousemove = function(e) {
var left = e.clientX - offset(yuantu).left - 100;
var top = e.clientY - offset(yuantu).top - 100;
var maskWidth = mask.offsetWidth / 2;
var maxX = yuantu.offsetWidth - maskWidth - 100
var maxY = yuantu.offsetHeight - maskWidth - 100
var scaleL = left/(yuantu.offsetWidth - mask.offsetWidth);
var scaleT = top/(yuantu.offsetWidth - mask.offsetWidth);
var bigImgW = enlargeImg.offsetWidth - enlarge.offsetWidth
var bigImgH = enlargeImg.offsetWidth - enlarge.offsetWidth
if (left <= 0) {
mask.style.left = 0 + "px";
} else if (left >= maxX) {
mask.style.left = maxX + "px";
} else {
mask.style.left = left + "px";
}
if (top <= 0) {
mask.style.top = 0 + "px";
} else if (top >= maxY) {
mask.style.top = maxY + "px";
} else {
mask.style.top = top + "px";
}
enlargeImg.style.left = -bigImgW * scaleL + 'px';
enlargeImg.style.top = -bigImgH * scaleT + 'px';
};
};
function offset(obj) {
var l = 0;
var t = 0;
var bdl = obj.clientLeft;
var bdt = obj.clientTop;
while (obj) {
l = l + obj.offsetLeft + obj.clientLeft;
t = t + obj.offsetTop + obj.clientTop;
obj = obj.offsetParent;
}
return { left: l - bdl, top: t - bdt };
}
</script>
</body>
</html>