js 实现放大镜功能
思路:
- 需要两个盒子(big+small),和一个遮罩(mark),两张图片(’.big img’+’.small img’)
- 随着鼠标的移动,遮罩跟着移动
运用知识:
- 根据遮罩的移动,计算大图与小图的比例 ,随之改变大图的top和left值移动到对应的位置上
const posi = - ( ′ . b i g i m g ′ ) . w i d t h ( ) / ('.big img').width()/ (′.bigimg′).width()/(’.small img’).width()
效果图:
上才艺:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.small{
width: 430px;
height: 430px;
position: absolute;
top: 100px;
left: 200px;
}
.big{
width: 430px;
height: 430px;
position:absolute;
top: 100px;
left: 650px;
overflow: hidden;
display: none;
border: 1px solid;
}
.mark{
width: 154px;
height: 154px;
position: absolute;
top: 0;
left: 0;
background-image: url('./img/dian.png');
cursor: move;
display: none;
}
.big img{
position: absolute;
left: 0;
top: 0;
}
</style>
</head>
<body>
<div class="small">
<div class="mark"></div>
<img src="./img/small.jpg" alt="">
</div>
<div class="big">
<img src="./img/big.jpg" alt="">
</div>
<script src="./js/jquery-3.6.0.js"></script>
<script src="./js/index.js"></script>
</body>
</html>
js内容(这里利用了jq)
$(function(){
$('.small').mouseover(()=>{
$('.big').show();
$('.mark').show()
})
$('.small').mouseout(()=>{
$('.big').hide();
$('.mark').hide()
})
// 鼠标移动事件 鼠标移动的最大范围
let maxL = $(".small").width()-$('.mark').width()
let maxT = $(".small").height()-$('.mark').height()
// 当鼠标进行移动时,利用鼠标的位置对遮罩位置进行绑定
$('.small').mousemove((ev)=>{
let l = ev.pageX-parseInt($(".mark").width()/2)-$('.small').offset().left;
let t = ev.pageY-parseInt($('.mark').height()/2)-$('.small').offset().top;
if(l>maxL){
l=maxL
}
if(l<0){
l=0
}
if(t>maxT){
t=maxT
}
if(t<0){
t=0
}
$('.mark').css({
'top':t,
'left':l
});
// 将大图片的位置与小图片的位置进行比例进行设置
const posi = -$('.big img').width()/$('.small img').width()
$('.big img').css({
'top': posi*t,
'left': posi*l
})
})
})