CSS样式
<style>
* {
margin: 0;
padding: 0;
}
.father {
margin: 100px;
width: 1000px;
height: 500px;
position: relative;
}
.small {
width: 295px;
height: 201px;
position: relative;
background-image: url(下载.jpg);
background-size: cover;
}
.small_a {
position: absolute;
top: 0;
left: 0;
height: 100px;
width: 100px;
background: rgba(0, 0, 0, .3);
display: none;
}
.big {
position: absolute;
top: 0px;
left: 295px;
width: 295px;
height: 201px;
overflow: hidden;
display: none;
}
.big img {
position: absolute;
display: block;
width: 295%;
height: 201%;
top: 0;
right: 0;
}
</style>
html样式
<div class="father">
<div class="small">
<div class="small_a"></div>
</div>
<div class="big">
<img src="下载.jpg" alt="">
</div>
</div>
JS样式
<script>
// 定义div
const small = document.querySelector(".small")
const bigImg = document.querySelector(".big img")
const b = document.querySelector(".big")
const smallA = document.querySelector(".small_a")
// 创建鼠标移入事件
small.onmouseover = function (e) {
// 进行事件委托,并且消除兼容性
e = e || window.event
// 鼠标移入后smallA与display属性为block
smallA.style.display = "block"
b.style.display = "block"
document.onmousemove = function (e) {
e = e || window.event
// 获取鼠标当前坐标
let startX = e.clientX-50
let startY = e.clientY-50
// 获取当前盒子的大小
let x=smallA.offsetWidth;
let y=smallA.offsetHeight;
// 将鼠标当前位置减去盒子大小
let addrresX=startX-x
let addrresY=startY-y
// 进行严谨化,设置临界值
// 当位置超过边界为负时,为0
if(addrresX<0){
addrresX=0
}
if(addrresY<0){
addrresY=0
}
// 当位置超过父级盒子大小减去自身盒子大小时为最大值
if(addrresX>small.clientWidth-x){
addrresX=small.clientWidth-x
}
if(addrresY>small.clientHeight-y){
addrresY=small.clientHeight-y
}
smallA.style.left=addrresX+"px"
smallA.style.top=addrresY+"px"
// 进行照片的倍数转换
// 原则为按比例划分 smallA/small的背景图=big/bigImg
// 所以当比例为X2.01,Y2.95
bigImg.style.top=-addrresY*2.01+"px"
bigImg.style.left=-addrresX*2.95+"px"
}
}
small.onmouseout = function (e) {
// 进行事件委托,并且消除兼容性
e = e || window.event
// 鼠标移出后smallA与display属性为none
smallA.style.display = "none"
b.style.display = "none"
// 鼠标移出后鼠标移动为null
document.onmousemove = null;
}
</script>