前提:感谢松妹,感谢松妹,感谢松妹
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
.small {
width: 300px;
height: 300px;
background-image: url(./index.png);
background-size: cover;
border: 10px solid pink;
float: left;
position: relative;
}
.magnifier {
width: 200px;
height: 200px;
position: absolute;
top: 0;
left: 0;
background-color: yellow;
opacity: 0.5;
display: none;
}
.big {
width: 450px;
height: 450px;
border: 10px solid pink;
float: left;
position: relative;
overflow: hidden;
display: none;
}
.big > img {
position: absolute;
width: 675px;
height: 675px;
}
</style>
</head>
<body>
<div class="small" id="small">
<div class="magnifier" id="magnifier"></div>
</div>
<div class="big" id="big">
<img src="./index.png" id="img">
</div>
</body>
<script type="text/javascript">
let smallBox = document.getElementById('small');
let magnifier = document.getElementById('magnifier');
let bigImg = document.getElementById('img');
let bigBox = document.getElementById('big');
smallBox.onmouseenter = function () { // 鼠标移入,显示放大镜和大图
bigBox.style.display = 'block';
magnifier.style.display = 'block';
}
smallBox.onmouseleave = function () { // 鼠标移出,隐藏放大镜和大图
bigBox.style.display = 'none';
magnifier.style.display = 'none';
}
smallBox.onmousemove = function (e) { // 放大镜移动事件
let left = e.clientX - 100;
let top = e.clientY - 100;
if (left <= 0) left = 0;
else if (left >= 100) left = 100;
if (top <= 0) top = 0;
else if (top >= 100) top = 100;
magnifier.style.left = left + 'px';
magnifier.style.top = top + 'px';
moveBigBox(left, top);
};
function moveBigBox (left, top) { // 移动右边图片
bigImg.style.left = `-${left * 2.25}px`; // (大盒子 / 小盒子) * (小盒子 / 放大镜)
bigImg.style.top = `-${top * 2.25}px`;
}
</script>
</html>