<!DOCTYPE html>
<html lang="zh">
<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>原生js实现放大镜效果</title>
<style type="text/css">
#box{
position: relative;
}
.small_img{
width:200px;
height: 200px;
position: absolute;
left: 0;
}
.small_img img{
width:100%;
height:100%;
}
.slide{
position: absolute;
left:0;
top:0;
width:100px;
height: 100px;
background: rgba(255,255,255,0.3);
cursor: move;
display: none;
z-index: 200;
}
.big_img{
position:absolute;
width:200px;
height: 200px;
left:210px;
overflow: hidden;
box-sizing: border-box;
border: 1px solid #000;
}
.big_img img{
width:400px;
height:400px;
position: absolute;
}
</style>
</head>
<body>
<div id="box">
<!--左侧-->
<div class="small_img">
<!--滑块-->
<div class="slide"></div>
<img src="jane.jpg" alt="" />
</div>
<!--右侧-->
<div class="big_img">
<img src="jane.jpg" alt="" class="jane"/>
</div>
</div>
</body>
</html>
<script src="demo.js"></script>
window.onload=function(){
//左侧图片元素
var smallImg=document.getElementsByClassName('small_img')[0];
//滑块元素
var slide=document.getElementsByClassName('slide')[0];
//右侧图片元素
var bigImg=document.getElementsByClassName('big_img')[0];
//图片
var jane=document.getElementsByClassName('jane')[0];
//针对左侧添加移入、移出事件
//移入
smallImg.onmousemove=function(event){
//滑块显示
slide.style.display="block";
//大图显示
bigImg.style.display="block";
//e.clientX当前移入点的位置 - slide.offsetWidth/2=滑块距离左侧x的位置
var left=event.clientX-slide.offsetWidth/2;
//e.clientY当前移入点的位置 - slide.offsetHeight/2=滑块距离顶部y的位置
var top=event.clientY-slide.offsetHeight/2;
//最大移动的范围
if(left<0){
left=0;
}else if(left>smallImg.offsetWidth-slide.offsetWidth){
left=smallImg.offsetWidth-slide.offsetWidth;
}
if(top<0){
top=0;
}else if(top>smallImg.offsetHeight-slide.offsetHeight){
top=smallImg.offsetHeight-slide.offsetHeight;
}
//给滑块的left和top值赋值
slide.style.left=left+'px';
slide.style.top=top+'px';
//右侧图片赋值 *2的原因是两边的关系是1:2 刚好左边是右边的一半,所以右侧的图片必须是2倍的关系
//比例=大图:小图
jane.style.left=-left*2+'px';
jane.style.top=-top*2+'px';
}
//移出
smallImg.onmouseout=function(){
//滑块隐藏
slide.style.display="none";
//大图显示
bigImg.style.display="none";
}
}