css部分
* {
margin: 0;
padding: 0;
}
#smallImg {
width: 300px;
height: 300px;
background-image: url(./lou.jpg);
background-size: cover;
}
#smallDiv {
width: 100px;
height: 100px;
background-color: rgba(255, 0, 0, 0.2);
display: none;
position: absolute;
}
#bigDiv {
width: 300px;
height: 300px;
position: absolute;
left: 300px;
top: 0px;
overflow: hidden;
display: none;
}
#bigImg {
width: 900px;
height: 900px;
position: absolute;
margin: 10px;
}
html部分
<div class="fang">
<div id="smallImg">
<div id="smallDiv"></div>
</div>
<div id="bigDiv">
<img src="./lou.jpg" alt="" id="bigImg" />
</div>
</div>
js部分
let smallImg = document.getElementById("smallImg");
let smallDiv = document.getElementById("smallDiv");
let bigDiv = document.getElementById("bigDiv");
let bigImg = document.getElementById("bigImg");
smallImg.onmouseover = function () {
smallDiv.style.display = "block";
bigDiv.style.display = "block";
};
smallImg.onmouseout = function () {
smallDiv.style.display = "none";
bigDiv.style.display = "none";
};
smallImg.onmousemove = function (e) {
var e = e || window.event;
var x = e.clientX - 100;
var y = e.clientY - 100;
if (x >= 200) {
x = 200;
}
if (x <= 0) {
x = 0;
}
if (y >= 200) {
y = 200;
}
if (y <= 0) {
y = 0;
}
smallDiv.style.left = x + "px";
smallDiv.style.top = y + "px";
bigImg.style.left = -3 * x + "px";
bigImg.style.top = -3 * y + "px";
};