效果图:
HTML代码:
<div class="preview_img">
<img src="upload/thumb_400_e3d1bdbf9fd07d9559ee2d3ff3ffe566.png" alt="">
<div class="mask"></div>
<div class="big">
<img src="upload/big.jpg" alt="" class="bigImg">
</div>
</div>
css代码:
.preview_img{
position: relative;
height: 400px;
border: 1px solid #ccc;
}
.mask{
position: absolute;
top: 0;
left: 0;
width: 300px;
height: 288px;
background-color: #FEDE4F;
opacity: .5;
}
.big{
position: absolute;
left: 410px;
top: 0;
width: 500px;
height: 500px;
z-index: 999;
border: 1px solid #ccc;
overflow: hidden;
}
.big img{
position: absolute;
top: 0;
left: 0;
}
注意:big里的照片设置成absolute定位才可以移动
js代码:
//手机详情图放大镜效果
var preview_img =document.querySelector('.preview_img');
var mask=document.querySelector('.mask');
var big=document.querySelector('.big');
//1.当我们鼠标经过preview_img,就显示和隐藏mask遮挡层和big大盒子
preview_img.addEventListener('mouseover',function(){
mask.style.display='block';
big.style.display='block';
})
//2.鼠标移动的时候让黄色的盒子跟着鼠标走
preview_img.addEventListener('mouseout',function(){
mask.style.display='none';
big.style.display='none';
})
preview_img.addEventListener('mousemove',function(e){
var x =e.pageX-this.offsetLeft;
var y =e.pageY-this.offsetTop;
var maskX=x-mask.offsetWidth/2;
var maskY=y-mask.offsetHeight/2;
//遮挡层最大移动距离
var maskMax=preview_img.offsetWidth-mask.offsetWidth;
if(maskX<=0){
maskX=0;
}else if(maskX>=maskMax){
maskX=maskMax;
}
if(maskY<=0){
maskY=0;
}else if(maskY>=maskMax){
maskY=maskMax;
}
mask.style.left=maskX+'px';
mask.style.top=maskY+'px';
//大图片移动距离=遮挡层移动距离*大图片最大移动距离/遮挡层最大移动距离
var bigImg=document.querySelector('.bigImg');
//大图片最大移动距离
var bigMax=bigImg.offsetWidth-big.offsetWidth;
var bigX=maskX*bigMax/maskMax;
var bigY=maskY*bigMax/maskMax;
bigImg.style.left=-bigX+'px';
bigImg.style.top=-bigY+'px';
})