用jQuery实现放大镜的功能
- 鼠标经过小盒子让大盒子和遮罩层显示与隐藏
- 求出鼠标在盒子里面的位置
- 让鼠标在遮罩层的中间位置
- 遮罩层能移动的最大距离
- 限制遮罩层上下左右的位置
- 赋值给遮罩层
- 求出大图移动距离
- 给大图的赋值
* {
margin: 0;
padding: 0;
}
.smallBox {
position: relative;
width: 400px;
height: 300px;
}
.img_1 {
width: 100%;
height: 100%;
}
.bigBox {
overflow: hidden;
display: none;
position: relative;
position: absolute;
top: 10px;
left: 450px;
width: 800px;
height: 600px;
border: 1px solid blue;
}
.img_2 {
position: absolute;
top: 0;
left: 0;
}
.mask {
display: none;
position: absolute;
top: 0;
left: 0;
width: 200px;
height: 200px;
background-color: yellow;
opacity: 0.5;
}
<div class="smallBox">
<img src="./img/cr.jpg" alt="" class="img_1" />
<div class="mask"></div>
</div>
<div class="bigBox">
<img src="./img/cr.jpg" alt="" class="img_2" />
</div>
$('.smallBox').mouseover(function() {
$(this).children('.mask').show()
$(this).siblings('.bigBox').show()
})
$('.smallBox').mouseleave(function() {
$(this).children('.mask').hide()
$(this).siblings('.bigBox').hide()
})
$('.smallBox').mousemove(function(e) {
var x = e.pageX - $(this).offset().left
var y = e.pageY - $(this).offset().top
var maskLeft = x - $('.mask').width() / 2
var maskTop = y - $('.mask').height() / 2
var maskMaxLeft = $('.smallBox').width() - $('.mask').width()
var maskMaxTop = $('.smallBox').height() - $('.mask').height()
if (maskLeft < 0) {
maskLeft = 0
} else if (maskLeft > maskMaxLeft) {
maskLeft = maskMaxLeft
}
if (maskTop < 0) {
maskTop = 0
} else if (maskTop > maskMaxTop) {
maskTop = maskMaxTop
}
$('.mask').css({
left: maskLeft,
top: maskTop
})
var img2MaxLeft = $('.img_2').width() - $('.bigBox').width()
var img2MaxTop = $('.img_2').height() - $('.bigBox').height()
var img2Left = (maskLeft * img2MaxLeft) / maskMaxLeft
var img2Top = (maskTop * img2MaxTop) / maskMaxTop
$('.img_2').css({
left: -img2Left,
top: -img2Top
})
})
![在这里插入图片描述](https://img-blog.csdnimg.cn/20201213164336245.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl8zODAwNzk4Ng==,size_16,color_FFFFFF,t_70#pic_center)