The effect is as follows: the
code is as follows: implemented with native js, the comments are in the code, if you don’t understand, you can leave a message to discuss
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>放大镜</title>
<style>
*{
margin: 0;
padding: 0;
}
.box{
margin-top: 50px;
margin-left: 100px;
}
.small{
cursor: all-scroll
}
.small img{
width: 400px;
height: 500px;
}
.small,
.big{
width: 400px;
height: 500px;
vertical-align: top;
position: relative;
display: inline-block;
}
.big{
overflow: hidden;
}
.big img{
display: none;
position: absolute;
width: 800px;
top: 0;
left: 0;
}
.zhezhaoceng{
width: 150px;
height: 150px;
background:rgba(0, 0, 0,.3);
position: absolute;
top: 0;
left:0;
z-index: 999;
}
</style>
</head>
<body>
<div class="box">
<!-- 原图 -->
<div class="small">
<img src="./images/small.png" alt="" class="smallimg">
<!-- //遮罩层 -->
<div class="zhezhaoceng"></div>
</div>
<!-- 放大后-->
<div class="big">
<img src="./images/big.jpg" alt="" class="bigimg">
</div>
</div>
<script>
var small=document.getElementsByClassName('small')[0];
var big=document.getElementsByClassName('big')[0];
var bigimg=document.getElementsByClassName('bigimg')[0];
var smallimg=document.getElementsByClassName('smallimg')[0];
var zhezhaoceng=document.getElementsByClassName('zhezhaoceng')[0];
small.onmouseover=function(){
bigimg.style.display='block';
document.onmousemove=function(e){
var e=e||window.event;
var movingY=e.pageY-small.offsetTop-zhezhaoceng.offsetHeight/2;
var movingX=e.pageX-small.offsetLeft-zhezhaoceng.offsetWidth/2;
//判断是否超出界限
movingY=movingY<0?0:movingY;
movingY=movingY>small.offsetHeight-zhezhaoceng.offsetHeight?small.offsetHeight-zhezhaoceng.offsetHeight:movingY;
movingX=movingX<0?0:movingX;
movingX=movingX>small.offsetWidth-zhezhaoceng.offsetWidth?small.offsetWidth-zhezhaoceng.offsetWidth:movingX;
// console.log(movingY);
// console.log(movingX);
zhezhaoceng.style.top=movingY+'px';
zhezhaoceng.style.left=movingX+'px';
//设置右边图片移动
//遮挡层的移动距离/遮挡层的最大移动距离=大图的移动距离/大图的最大移动距离
//大图的移动距离=遮挡层的移动距离*大图的最大移动距离/遮挡层的最大移动距离
//大图最大移动距离
var bigMaxY=bigimg.offsetHeight-big.offsetHeight;
var bigMaxX=bigimg.offsetWidth-big.offsetWidth
//遮罩层最大移动距离
var zheY=smallimg.offsetHeight-zhezhaoceng.offsetHeight;
var zheX=smallimg.offsetWidth-zhezhaoceng.offsetWidth;
//计算大图移动距离
var bigimgLeft=movingX*bigMaxX/zheX;
var bigimgTop=movingY*bigMaxY/zheY;
//赋值
bigimg.style.top=-bigimgTop+'px';
bigimg.style.left=-bigimgLeft+'px';
}
}
small.onmouseout=function(){
bigimg.style.display='none';
}
</script>
</body>
</html>