<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
html,
body {
width: 100%
height: 100%
}
.test {
width: 80%
height: 1200px
padding: 50px
border: 1px solid
}
width: 200px
height: 300px
border: 1px solid green
position: absolute
top: 100px
left: 100px
background: url('./img/texs1x.jpg') no-repeat
background-size: 200px 300px
}
display: none
position: absolute
width: 100px
height: 150px
background-color: skyblue
opacity: 0.3
pointer-events: none
/* 这个很关键,取消参与鼠标事件,这样就可以用 e.offsetX/ e.offsetY了 */
}
display: none
width: 300px
height: 450px
border: 1px solid blue
position: absolute
top: 0
left: 210px
overflow: hidden
}
position: absolute
top: 0
left: 0
}
</style>
</head>
<body>
<div class="test">
<div id="wrap">
<div id="mask"></div>
<div id="show">
<img id="big" src="./img/test3x.jpg" alt="">
</div>
</div>
</div>
<script>
const wrap = document.getElementById('wrap')
const mask = document.getElementById('mask')
const show = document.getElementById('show')
const big = document.getElementById('big')
console.dir(mask)
let x = null
let y = null
wrap.onmouseover = function () {
mask.style.display = 'block'
show.style.display = 'block'
}
wrap.onmouseout = function () {
mask.style.display = 'none'
show.style.display = 'none'
}
wrap.onmousemove = function (e) {
e.preventDefault()
const x1 = wrap.clientWidth
const y1 = wrap.clientHeight
const x2 = mask.offsetWidth
const y2 = mask.offsetHeight
const x3 = show.clientWidth
const y3 = show.clientHeight
x = e.offsetX
y = e.offsetY
// 使用以上获取鼠标位置更加精准,不受定位等限制
// 使用pageX-offsetLeft的话,如果外部有定位的话,offsetLeft得不到理想的数据
if (x < x2 / 2) {
x = 0
} else if (x > x1 - (x2 / 2)) {
x = x1 - x2
} else {
x = x - (x2 / 2)
}
if (y < y2 / 2) {
y = 0
} else if (y > y1 - (y2 / 2)) {
y = y1 - y2
} else {
y = y - (y2 / 2)
}
mask.style.left = x + 'px'
mask.style.top = y + 'px'
big.style.left = -x * (x3 / x2) + 'px'
big.style.top = -y * (y3 / y2) + 'px'
}
</script>
</body>
</html>