一:首先得要创建两个盒子设置大小,图片自己可以在网上寻找
<div id="left" style="background: url(./img/5a445ba0N2b96e844.jpg) 0 / 100% 100%;"></div>
<div id="right" style="background: url(./img/5a445ba0N2b96e844.jpg) center; background-size: 200% 200%;"></div>
css样式:
<style>
#left{
width: 300px;
height: 300px;
background: red;
margin: 50px;
}
#right{
width: 500px;
height: 500px;
border: 1px solid #ccc;
background: green;
position: absolute;
top: 0;
left: 300px;
background-repeat: no-repeat;
}
</style>
二:其中鼠标放入消失和出现不是难点,主要是计算距离和将其转换成百分比
<script>
function $(str){
return document.querySelector(str)
}
window .onload =function(){
let l =$('#left').offsetLeft +$('#left').offsetWidth
let t =$('#left').offsetTop
$('#right').style.left =l +'px'
$('#right').style.top =t +'px'
$('#left').onmouseenter =() =>{
$('#right').style.display ='block'
}
$('#left').onmouseleave =() =>{
$('#right').style.display ='none'
}
$('#left').onmousemove =(e)=>{
let x = e.pageX -$('#left').offsetLeft
let y = e.pageY -$('#left').offsetTop
x=x/$('#left').offsetWidth
y=y/$('#left').offsetHeight
x=(x*100).toFixed(4)+"%" //百分比
y=(y*100).toFixed(4)+"%" //百分比
$("#right").style['background-position-x']=x
$("#right").style['background-position-y']=y
} }
</script>