<!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-img,.big-img{
width:300px;
height:300px;
overflow:hidden;
display: inline-block;
border:1px dotted gray;
}
.small-img{
margin-right:30px;
position: relative;
}
.small-img img{
width:100%;
height:100%;
}
.big-img img{
width:1200px;
height:1200px;
}
.big-img{
display: none;
}
.tool{
width:100px;
height:100px;
background:rgba(0,0,0,.2);
position: absolute;
top:0;
left:0;
pointer-events: none;
display: none;
}
</style>
</head>
<body>
<div class="small-img">
<img src="timg.jpeg" alt="">
<span class="tool"></span>
</div>
<div class="big-img">
<img src="timg.jpeg" alt="">
</div>
<script>
window.onload=function(){
let obj={
findElem:el=>document.querySelector(el),
moveTool:function({tool,smallImg,bigImg,toolWidth,smallIMgWidth,x,y,scale}){
let left=0,top=0;
x<=toolWidth/2?left=0:left=x-toolWidth/2;
y<=toolWidth/2?top=0:top=y-toolWidth/2;
if(x>=(smallIMgWidth-toolWidth/2)){
left=smallIMgWidth-toolWidth
}
if(y>=(smallIMgWidth-toolWidth/2)){
top=smallIMgWidth-toolWidth;
}
tool.style.top=top+'px';
tool.style.left=left+'px';
bigImg.style.transform=`translate(${-scale*x}px,${-scale*y}px)`;
},
init:function(){
let tool=this.findElem('.tool')
, smallImg=this.findElem('.small-img')
, bigRight=this.findElem('.big-img')
, bigImg=this.findElem('.big-img img')
,bigImgWidth=bigImg.clientWidth
,toolWidth=tool.clientWidth
,smallIMgWidth=smallImg.clientWidth,
that=this;
smallImg.addEventListener('mouseover',(e)=>{
tool.style.display="block";
bigRight.style.display="block";
toolWidth=tool.clientWidth;
bigImgWidth=bigImg.clientWidth
})
smallImg.addEventListener('mouseout',(e)=>{
tool.style.display='none';
bigRight.style.display="none";
})
smallImg.addEventListener('mousemove',(e)=>{
let obj1={
tool,
smallImg,
bigImg,
toolWidth,
smallIMgWidth,
x:e.offsetX,
y:e.offsetY,
scale:bigImgWidth/smallIMgWidth
}
that.moveTool(obj1);
})
}
}
obj.init();
}
</script>
</body>
</html>