js实现放大镜效果

js实现放大镜效

首先放大镜的原理,通过调整移动距离比例,由左方小图片中移动小方框,显示右边提前设置好的窗口中放大的局部图片(图片可以自己去网上找,最下方小编会放入原代码,略微修改图片地址和css宽高便可使用)
在这里插入图片描述首先我们先搭出html结构
在这里插入图片描述设置两个盒子左小右大,左边盒子与图片大小一致即可(也可以自己设置),分别放入图片(自己随意添加),再向第一个盒子中写入一个小盒子,方便后面做拖动显示哪一部分。
第二部搭建css
在这里插入图片描述
这是笔者设置的css,需要注意的点是要设置盒子1中small的透明度方便可以看见盒子1的最底层图片,盒子2设置宽高,设置溢出隐藏,将多余部分隐藏,小编这里在js最后设置了鼠标移入显示粉色区域和盒子2,因此可能只写html和css效果不太明显,
第三部,则是实现js部分,通过移动左边小框来同步实现右边图片等比例向反方向移动
在这里插入图片描述

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
*{
	padding:0;
	margin:0;
 }
 body{
  	font-size:0;
 }
 #box1{
  width:350px;
  height:350px;
  float:left;
  position:relative;
 }
 #box2{
  width:400px;
  height:400px;
  overflow:hidden; 
  float:left;
  position:relative;
 }
 #small{
  width:180px;
  height:180px;
  background:pink;
  opacity:0.4;
  position:absolute;
  top:0;
  left:0;
 }
 #photo{
  position:absolute;
  top:0;
  left:0;
 }
 .active{
  display:block;
 }
 .close{
  display:none;
 }
</style>
</head>
<body>
<div id="box1">
 <img src="img/small.jpg" alt="pho" id="jpg">
 <div id="small" class="close"></div>
</div>
<div id="box2" class="close">
 <img src="img/big.jpg" alt="pho" id="photo">
</div>
<script>
 var box1 = document.getElementById('box1'),//获取节点部分
  box2 = document.getElementById('box2'),
  small = document.getElementById('small'),
  photo = document.getElementById('photo');
 var oLeft=0,oTop=0,x=0,y=0,m=0,n=0;
 box1.onmouseenter = function(){//设置移入显示事件
  box2.className = 'active';
  small.className = 'active';
 }
 box1.onmouseleave = function(){//设置移除隐藏事件
  box2.className = 'close';
  small.className = 'close';
 }
 small.onmousedown = function(e){设置鼠标按下事件
  x = e.clientX-this.offsetLeft;
  y = e.clientY-this.offsetTop;
  document.onmousemove = function(e){设置鼠标移动事件
   oLeft = e.clientX-x;
   oTop = e.clientY-y;
   if(oLeft<=0){//设置small的移动范围为盒子1
    oLeft = 0;
   }
   if(oLeft>=box1.offsetWidth-small.offsetWidth){
    oLeft = box1.offsetWidth-small.offsetWidth;
   }
   if(oTop<=0){
    oTop = 0;
   }
   if(oTop>=box1.offsetHeight-small.offsetHeight){
    oTop = box1.offsetHeight-small.offsetHeight;
   }
   m = -(parseInt(((photo.offsetWidth+x)/box2.offsetWidth)*oLeft));
   //核心代码等比例移动
   n = -(parseInt(((photo.offsetHeight+y)/box2.offsetHeight)*oTop));
   small.style.left = oLeft+'px';
   photo.style.left = m+'px';
   small.style.top = oTop+'px';
   photo.style.top = n+'px';
  }.bind(this)
  document.onmouseup = function(e){//设置鼠标移除事件
   document.onmousemove = 'null';
   document.onmouseup = 'null';
  }
 }
</script>
</body>
</html>

最终实现效果,当然这是简易版的放大镜效果,大家可以在此基础上继续实现的更完美在这里插入图片描述

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值