CSS部分
<style>
.wrapper{
margin: 0 auto;
width: 1000px;
display: flex;
}
.big{
position: relative;
width: 430px;
height: 430px;
overflow: hidden;
display: block;
}
.little{
position: relative;
width: 430px;
height: 430px;
}
.big img{
width: 860px;
position: absolute;
left: 0;
top: 0;
}
.mark{
position: absolute;
top: 0;
left: 0;
width: 215px;
height: 215px;
background-color: gray;
opacity: .3;
display: none;
}
</style>
HTML部分
<div class="wrapper">
<div class="little">
<img src="../IMGS/商品页/22.jpg" alt="">
<div class="mark"></div>
</div>
<div class="big">
<img src="../IMGS/商品页/22.jpg" alt="">
</div>
</div>
<script>
//获取元素
var _little=document.querySelector(".little")
var _mark=document.querySelector(".mark")
var _big=document.querySelector(".big")
var _img=document.querySelector(".big img"); //大图
_little.onmouseover=function(){
_big.style.display="block"
_mark.style.display="block"
}
//给小图添加事件
_little.onmousemove=function(event){
//获取图片的位置
var dx=event.clientX-_little.offsetLeft-_mark.offsetWidth/2
var dy=event.clientY-_little.offsetTop-_mark.offsetHeight/2
//设置边界
if(dx>_little.offsetWidth-_mark.offsetWidth){
dx=_little.offsetWidth-_mark.offsetWidth;
}
if(dx<=0){
dx=0;
}
_mark.style.left=dx+"px";
if(dy>_little.offsetHeight-_mark.offsetHeight){
dy=_little.offsetHeight-_mark.offsetHeight;
}
if(dy<=0){
dy=0;
}
_mark.style.top=dy+"px";
//大图*2
_img.style.left=dx*-2+"px"
_img.style.top=dy*-2+"px"
}
</script>
JS部分