话不多说,直接先上效果图
效果图
放大镜 (2).gif文件结构图:
1569806498039.png
上代码:
CSS
*{
margin: 0;
padding: 0;
}
.container{
margin: 20px auto;
width: 650px;
/*height: 300px;*/
}
.container .smallBox{
position: relative;
float: left;
width: 300px;
height: 300px;
overflow: hidden;
}
.container .smallBox img{
display: block;
width: 100%;
height: 100%;
}
.mark{
position: absolute;
left: 0;
top: 0;
width: 100px;
height: 100px;
background: rgba(220, 20, 164,0.3);
cursor: move;
}
.bigBox{
position: relative;
float: left;
width: 350px;
height: 350px;
overflow: hidden;
}
.bigBox img{
position: absolute;
top: 0;
left: 0;
/*mark:small-box===big-box:大img*/
width: 1050px;
height: 1050px;
}
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<link rel="stylesheet" href="magnifier.css">
<body>
<!--section.magnifierBox>(div.smallBox>img[src='img/缩小.jpg']+div.mark)+(div.bigBox>img[src='img/放大.jpg'])-->
<section class="container clearfix">
<div class="smallBox">
<img src="img/小.jpg" alt="">
<!--<div class="mark"></div>-->
</div>
<div class="bigBox"><img src="img/小.jpg" alt=""></div>
</section>
<script src="magnifier.js"></script>
</body>
JS
let smallBox=document.querySelector('.smallBox'),
mark=null;
let bigBox=document.querySelector('.bigBox'),
bigImg=bigBox.querySelector('img');
//=>鼠标滑过:创建mark
smallBox.onmouseenter=function(){
if(!mark){
mark=document.createElement('div');
mark.className='mark';
this.appendChild(mark);
bigBox.style.display='block';
}
};
//=>鼠标移动实现mark跟随鼠标移动
smallBox.onmousemove=function(ev){
if(!mark) return;
//计算鼠标在盒子中间的left和top
let curL=ev.pageX-smallBox.offsetLeft-mark.offsetWidth/2,
curT=ev.pageY-smallBox.offsetTop-mark.offsetHeight/2;
//计算的值不能超过边界
let minL=0,minT=0,
maxL=smallBox.offsetWidth-mark.offsetWidth,
maxT=smallBox.offsetHeight-mark.offsetHeight;
curL=curL<minL?minL:(curL>maxL?maxL:curL);
curT=curT<minT?minT:(curT>maxL?maxT:curT);
//给markz赋值样式,让其移动到指定位置
mark.style.left=curL+'px';
mark.style.top=curT+'px';
bigImg.style.left=-curL*3.5+'px';
bigImg.style.top=-curT*3.5+'px';
}
//=>鼠标离开,移除mark
smallBox.onmouseleave=function(){
if(mark){
this.removeChild(mark);//从页面中移除mark,但是此时mark变量依然存储着之前的值(页面移除是DOM操作,但是mark是js变量没啥关系)
mark=null;//=>手动赋值为null,代表mark已经不存在了
bigBox.style.display='none';
}
};
网友评论