HTML代码
<div class="box">
<img src="img/08.jpg"/>
<div class="slider"></div>
</div>
<div class="lens">
<img src="img/08.jpg"/>
</div>
CSS代码
*{margin: 0;padding: 0;}
.box{
width: 500px;
height: 500px;
border:1px solid black;
position: relative;
display: inline-block;
margin-left:200px;
}
.box img{width: 100%;height: 100%;}
.slider{
width:250px;
height: 250px;
position: absolute;
left:0;
top:0;
background: rgba(0,0,255,0.3);
display: none;
cursor: move;
}
.lens{
display: inline-block;
width:500px;
height:500px;
overflow: hidden;
position: relative;
display: none;
}
.lens img{
width:1000px;
height:1000px;
position: absolute;
top:0;
left:0;
}
JS代码
var slider=document.querySelector(".slider")
var box =document.querySelector(".box")
var img =document.querySelector(".lens img")
var lens =document.querySelector(".lens")
box.onmousemove=function(e){ //给大盒子添加onmousemove事件
var w=slider.offsetWidth //获取小滑块的宽度
var h=slider.offsetHeight //获取小滑块的高度
// console.log(w,h) //获取小滑块的宽高
var scale=box.offsetWidth/w
//倍数 用大盒子的宽除以小滑块的宽
e=e||window.event
// console.log(e)
var x=e.pageX-this.offsetLeft-w/2
//e.pageX获取移动的坐标x轴 //-w/2 让小滑块到正中心
//this.offsetLeft this指代box offsetLeft距离的就是body 大盒子的父级
var y=e.pageY-this.offsetTop-h/2
//e.pageY获取移动的坐标x轴
// console.log(x,y);
//判断x,y不让小滑块出去
if(x>box.offsetWidth-w){ //右边 大盒子的宽减去小盒子的宽
x=box.offsetWidth-w
}else if(x<0){
x=0 //左边 不让出去
}
if(y>box.offsetHeight-h){
y=box.offsetHeight-h
}else if(y<0){
y=0
slider.style.left=x+"px" //让小滑块动起来
slider.style.top=y+"px"
img.style.left=-x*scale+"px" //让放大的图片也跟着动起来
img.style.top=-y*scale+"px" //加负值 正的会跟着移动
} //滑块移动和图片移动是相反的
box.onmouseenter=function () {
lens.style.display="inline-block"
slider.style.display="block"
}
box.onmouseleave=function () {
lens.style.display="none"
slider.style.display="none"
}