HTML代码
<div id="box" style="display: flex">
<div id="left">
<img src="img/timg.jpg"/>
<div id="square" style="display: none"></div>
</div>
<div id="right" style="display: none">
<img src="img/timg.jpg" >
</div>
</div>
CSS代码
*{
margin: 0;
padding: 0;
}
img{
display: block;
width: 100%;
height: 100%;
}
#left{
width: 540px;
height: 360px;
margin: 30px 0 0 50px;
position: relative;
}
#square{
width: 270px;
height: 180px;
background: rgba(0,0,0,0.2);
position: absolute;
left: 0;
top: 0;
}
#right{
width: 540px;
height: 360px;
overflow: hidden;
margin: 30px 0 0 50px;
position: relative;
border: 1px solid red;
}
#right img{
width: 1080px;
height: 720px;
position: absolute;
left: 0;
top: 0;
}
JS代码
$(document).ready(function(){
var img=$('#right img');
var times=img.width()/$('#left img').width();
$('#left').mousemove(function(e){//e.clientX e.clientY鼠标相对于窗口左上角的位置
//鼠标移入的时候 方块显示出来
$('#square').show();
$('#right').show();
//计算鼠标在div中的距离
var left=e.clientX-$('#left').offset().left;
var top=e.clientY-$('#left').offset().top;
// console.log(left,top)
//所以正方形必须跟着鼠标在里面移动 但是必须要让正方形在鼠标的中间
var squareWidth=$('#square').width(),squareHeight=$('#square').height();
var squareLeft=$('#square').offset().left,squareTop=$('#square').offset().top;
$('#square').css({'top':top-(squareHeight/2)+'px','left':left-(squareWidth/2)+'px'});
//在这里需要判断 正方形靠近边缘的情况
if(left<=squareWidth/2){//代表方块已经在最左边
$('#square').css('left',0)
}
if(top<=squareHeight/2){//代表方块已经在最上边
$('#square').css('top',0)
}
if(left>$('#left').width()-(squareWidth/2)){//代表方块在最右边
$('#square').css('left',$('#left').width()-squareWidth+'px');
}
if(top>$('#left').height()-(squareHeight/2)){//代表方块在最下边
$('#square').css('top',$('#left').height()-squareHeight+'px')
}
//因为left盒子有一个margin-left和margin-top 所以导致放大镜的offset().left和top有一个margin的值
img.css('left',-(squareLeft-$('#left').offset().left)*times+'px')
img.css('top',-(squareTop-$('#left').offset().top)*times+'px')
});
$('#left').mouseout(function(e){
//鼠标移出的时候 方块隐藏
$('#square').hide();
$('#right').hide();
})
})
因为是按照2两倍的倍数进行放大的,所以放大镜的高度和外面盒子的1/2,外面的盒子又是放大之后图片的1/2。
网友评论