代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>放大镜</title>
<style>
* {
margin: 0;
padding: 0;
}
#box {
margin-top: 10px;
}
#small-box {
width: 300px;
height: 225px;
float: left;
margin-left: 50px;
position: relative;
border: 1px solid #000;
}
#big-box {
width: 300px;
height: 300px;
overflow: hidden;
float: left;
margin-left: 30px;
position: relative;
border: 1px solid #000;
display: none;
}
#big-box img {
position: absolute;
top: 0;
left: 0;
}
.mask {
width: 100px;
height: 100px;
background-color: #000;
opacity: 0.3;
position: absolute;
top: 0;
left: 0;
cursor: move;
display: none;
}
</style>
</head>
<body>
<div id="box">
<div id="small-box">
<img src="img/smallpic.jpg" alt="">
<span class="mask"></span>
</div>
<div id="big-box">
<img src="img/bigpic.jpg" alt="">
</div>
</div>
<script>
let smallBox = document.querySelector("#small-box")
let mask = document.querySelector(".mask")
let bigBox = document.querySelector("#big-box")
let bigImg = document.querySelector("#big-box img")
smallBox.onmousemove = function (e) {
let myleft = e.clientX - smallBox.offsetLeft - mask.offsetWidth / 2
let mytop = e.clientY - smallBox.offsetTop - mask.offsetHeight / 2
if (myleft < 0) {
myleft = 0
}
if (myleft > smallBox.offsetWidth - mask.offsetWidth) {
myleft = smallBox.offsetWidth - mask.offsetWidth
}
if (mytop < 0) {
mytop = 0
}
if (mytop > smallBox.offsetHeight - mask.offsetHeight) {
mytop = smallBox.offsetHeight - mask.offsetHeight
}
mask.style.left = myleft + "px"
mask.style.top = mytop + "px"
bigImg.style.left = -myleft * bigImg.offsetWidth / smallBox.offsetWidth + "px"
bigImg.style.top = -mytop * bigImg.offsetHeight / smallBox.offsetHeight + "px"
}
smallBox.addEventListener("mouseenter", () => {
mask.style.display = "block"
bigBox.style.display = "block"
})
smallBox.addEventListener("mouseleave", () => {
mask.style.display = "none"
bigBox.style.display = "none"
})
</script>
</body>
</html>