css部分:
* {
margin: 0;
padding: 0;
}
#normal {
width: 400px;
height: 400px;
position: relative;
border: 1px red solid;
}
#small {
background: red;
}
#small img {
width: 400px;
height: 400px;
}
.big {
position: absolute;
height: 400px;
width: 400px;
left: 450px;
top: 0;
overflow: hidden;
display: none;
border: 1px red solid;
}
.big-img {
position: absolute;
left: 0;
top: 0;
}
.box {
width: 200px;
height: 200px;
background: rgba(255, 255, 0, 0.3);
position: absolute;
left: 0px;
top: 0px;
display: none;
}
HTML部分:
<div id="normal">
<div id="small">
<img src="../images/normal.jpg" alt="" />
<div class="box"></div>
</div>
<div class="big">
<img src="../images/big.jpg" alt="" class="big-img" />
</div>
</div>
JS部分:
const normal = document.querySelector("#normal");
const box = document.querySelector(".box");
const bigDiv = document.querySelector(".big");
const bigImg = document.querySelector(".big-img");
normal.onmouseenter = function () {
box.style.display = "block";
bigDiv.style.display = "block";
let bigImgWidth =
(bigDiv.offsetWidth * normal.offsetWidth) / box.offsetWidth;
};
normal.onmoouseleave = function () {
box.style.display = "none";
bigDiv.style.display = "none";
};
normal.onmousemove = function (evt) {
let offsetX = evt.pageX - normal.offsetLeft;
let offsetY = evt.pageY - normal.offsetTop;
let boxX = offsetX - box.offsetWidth / 2;
let boxY = offsetY - box.offsetHeight / 2;
if (boxX <= 0) {
boxX = 0;
}
if (boxY <= 0) {
boxY = 0;
}
if (boxX >= normal.offsetWidth - box.offsetWidth) {
boxX = normal.offsetWidth - box.offsetWidth;
}
if (boxY >= normal.offsetWidth - box.offsetWidth) {
boxY = normal.offsetWidth - box.offsetWidth;
}
box.style.left = boxX + "px";
box.style.top = boxY + "px";
let bigImgX = (-boxX * bigImg.offsetWidth) / normal.offsetWidth;
let bigImgY = (-boxY * bigImg.offsetHeight) / normal.offsetHeight;
bigImg.style.left = bigImgX + "px";
bigImg.style.top = bigImgY + "px";
};
运行结果:
![](https://i-blog.csdnimg.cn/blog_migrate/41aae35e81244c3f8509d37846ac8ba3.png)