首先我们先做一个div
<div id="left"></div>
<div id="right"></div>
之后css定位
#left{
width: 300px;
height: 300px;
margin: 150px;
background: url(1.png) 0 / 100% 100%;
border: 1px solid black;
}
#right{
width: 500px;
height: 500px;
position: absolute;
background: url(2.png) center;
top: 0;
display: none;
left: 300px;
}
获取元素,对要操作的元素添加事件,设置当前选中的图片以及实现放大镜的效果,使放大镜随着鼠标移动。
<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').offsetHeigth
x= (x * 100).toFixed(4) + "%"
y= (y * 100).toFixed(4) + "%"
$("#right").style['background-position-x'] = x
$("#right").style['background-position-y'] = y
}
}
</script>