效果图
html部分:
<div class="preview">
<img src="./img/柯南2.webp" alt="">
<div class="mask"></div>
<div class="big">
<img src="./img/柯南2.webp" alt="" class="big_img">
</div>
</div>
css部分
* {
padding: 0;
margin: 0;
}
.preview {
width: 500px;
height: 500px;
margin-left: 30px;
border: 1px solid #000;
text-align: center;
position: relative;
}
.preview>img {
width: 100%;
height: 500px;
object-fit: cover;
object-position: 0 0;
}
.mask {
display: none;
width: 200px;
height: 200px;
background-color: #fede4f;
opacity: 0.5;
position: absolute;
top: 0;
left: 0;
}
.big {
display: none;
width: 500px;
height: 500px;
background-color: pink;
position: absolute;
top: 0;
left: 510px;
z-index: 999;
overflow: hidden;
}
.big>img {
width:1200px;
position: absolute;
top: 0;
left: 0;
}
javascript部分:
$(document).ready(function(){
$(".preview").on("mouseenter",function(){
$(".mask").show()
$(".big").show()
})
$(".preview").on("mouseleave",function(){
$(".mask").hide()
$(".big").hide()
})
$(".preview").on("mousemove",function(e){
var x=e.pageX-$('.preview').offset().left
var y=e.pageY-$('.preview').offset().top
var maskX=x-$(".mask").width()/2
var maskY=y-$(".mask").height()/2
console.log(maskX);
if(maskX<=0){
maskX=0
}else if(maskX>=$('.preview').width()-$(".mask").width()){
maskX=$('.preview').width()-$(".mask").width()
}
if(maskY<=0){
maskY=0
}else if(maskY>=$('.preview').height()-$(".mask").height()){
maskY=$('.preview').height()-$(".mask").height()
}
$(".mask").css("left",maskX+"px").css("top",maskY+"px")
var maxLittleMove=$('.preview').width()-$(".mask").width()
var maxBigMove=$('.big_img').width()-$(".big").width()
$(".big_img").css("left",-maskX*maxBigMove/maxLittleMove+"px").css("top",-maskY*maxBigMove/maxLittleMove+"px")
})
})