<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
padding: 0px;
margin: 0px;
}
.box {
width: 400px;
height: 400px;
border: 1px solid;
position: relative;
cursor: move;
float: left;
}
.box2 {
width: 400px;
height: 400px;
border: 1px solid;
float: left;
background-image: url(./images/138a986c7a96f8ba.jpg);
background-position-x: -400px;
display: none;
}
.ye {
width: 200px;
height: 200px;
background: rgba(230, 247, 3, 0.5);
position: absolute;
z-index: 1;
display: none;
}
.box img {
width: 100%;
vertical-align: bottom;
}
</style>
</head>
<body>
<div class="box" id="box">
<div class="ye" id="ye"></div>
<img src="./images/138a986c7a96f8ba.jpg" alt="">
</div>
<div class="box2" id="box2"></div>
<script>
var box = document.getElementById("box");
var box2 = document.getElementById("box2");
var ye = document.getElementById("ye");
box.addEventListener("mouseover", function () {
ye.style.display = "block"
box2.style.display = "block"
})
box.addEventListener("mousemove", function (e) {
var x = e.clientX - this.offsetLeft;
var y = e.clientY - this.offsetTop;
var a_left = x - (ye.offsetWidth / 2)
console.log(a_left)
if (a_left <= 0) {
a_left = 0;
} else if (a_left >= (box.offsetWidth - ye.offsetWidth)) {
a_left = box.offsetWidth - ye.offsetWidth;
}
ye.style.left = a_left + "px"
var a_top = y - (ye.offsetHeight / 2);
if (a_top <= 0) {
a_top = 0;
} else if (a_top >= (box.offsetHeight - ye.offsetHeight)) {
a_top = box.offsetHeight - ye.offsetHeight;
}
ye.style.top = a_top + "px";
box2.style.backgroundPositionX = -(ye.offsetLeft * 2) + "px"
box2.style.backgroundPositionY = -(ye.offsetTop * 2) + "px"
})
box.addEventListener("mouseout", function () {
ye.style.display = "none"
box2.style.display = "none"
})
</script>
</body>
</html>