思路:通过获取鼠标的位置与相对smallbox的偏移量来查看当前大图的位置,注意:鼠标的移动方向相对于图片而言是反向的。

1.html
<div class="smallbox">
<div class="bjbox"></div>
</div>
<div class="bigbox"></div>
3.css
.smallbox {
width: 380px;
height: 288px;
position: absolute;
top: 100px;
left: 100px;
background: url(./img/small.png);
}
.bigbox {
width: 400px;
height: 400px;
position: absolute;
top: 100px;
right: 100px;
background: url(./img/big.jpg);
}
.bjbox {
position: absolute;
left: 0px;
top: 0px;
width: 100px;
height: 100px;
background: url(./img/bj.png);
}
3.js
const smallbox = document.querySelector(".smallbox")
const bjbox = document.querySelector(".bjbox")
const bigbox = document.querySelector(".bigbox")
smallbox.onmouseover = function () {
document.onmousedown = function () {
document.onmousemove = function (e) {
e = e || window.event
let x = e.clientX
let sbl = smallbox.offsetLeft
let sbt = smallbox.offsetTop
let y = e.clientY
let bjw = bjbox.offsetWidth
let bjh = bjbox.offsetHeight
let maxw = smallbox.offsetWidth - bjw
let maxh = smallbox.offsetHeight - bjh
let l = x - sbl - bjw / 2
let h = y - sbt - bjh / 2
l = l < 0 ? 0 : l;
l = l > maxw ? maxw : l
h = h < 0 ? 0 : h
h = h > maxh ? maxh : h
bjbox.style.left = l + "px"
bjbox.style.top = h + "px"
bigbox.style.backgroundPosition = `-${l*4}px -${h*4}px`
}
}
}
bjbox.onmouseup = function () {
document.onmousemove = !document.onmousemove
}