放大镜的实现

今天给大家实现放大镜的功能,也就是平时商城会经常用到的一种效果,其方法是,准备一张高像素的大图,当鼠标放到小图上,通过对大图进行绝对定位以此加载显示对应的位置,并且用mousemove事件的监听方法,当鼠标移到$small对象中,我们获取当前鼠标的相对坐标位置。

html的代码如下:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>放大镜</title>
		<link rel="stylesheet" href="css/fdj.css" />
		<script type="text/javascript" src="js/jquery-1.11.0.js" ></script>
	    <script type="text/javascript" src="js/index.js" ></script>
	</head>
	<body>
		<div class="box" id="box">
		  <div class="small"><!--小层-->
		    <img src="img/small.png" width="350" alt=""/>
		    <div class="mask"></div><!--遮挡层-->
		  </div><!--小图-->
		  <div class="big"><!--大层-->
		    <img src="img/big.jpg" width="800" alt=""/><!--大图-->
		  </div><!--大图-->
		</div>	
	</body>
</html>

 

css代码如下:

* {
  margin: 0;
  padding: 0;
}

.box {
  width: 350px;
  height: 350px;
  margin: 100px;
  border: 1px solid #ccc;
  position: relative;
}

.big {
  width: 400px;
  height: 400px;
  position: absolute;
  top: 0;
  left: 360px;
  border: 1px solid #ccc;
  overflow: hidden;
  display: none;
}

.mask {
  width: 175px;
  height: 175px;
  background: rgba(255, 255, 0, 0.4);
  position: absolute;
  top: 0px;
  left: 0px;
  cursor: move;
  display: none;
}

.small {
  position: relative;
}

js代码如下:

$(function(){
//	获取对象
	var $box=$("#box")
	var $small=$("#box .small")
	var $mask=$("#box .mask")
	var $big=$(".big")
	var $bigimg=$(".big img")
	
	$small.mouseenter(function(){
		$mask.css("display","block");
		$big.css("display","block")
	})
	$small.mouseleave(function(){
		$mask.css("display","none");
		$big.css("display","none")
	})
	
	$small.mousemove(function(e){
		var x=e.clientX-$mask.width()/2
		var y=e.clientY-$mask.height()/2
		x=x-100;
		y=y-100;
		x=x<0?0:x;
		y=y<0?0:y;
		
		x=x>$small.width()-$mask.width()?$small.width()-$mask.width():x;
		y=y>$small.height()-$mask.height()?$small.height()-$mask.height():y;
		
		$mask.css({"left":x,"top":y})
		
		
		
	var bigimgMoveX=$bigimg.width()-$big.width();//横向
	var bigimgMoveY=$bigimg.height()-$big.height()//纵向
		
		
	var bigimgMoveXX=(x*bigimgMoveX)/($small.width()-$mask.width())
	var bigimgMoveYY=(y*bigimgMoveY)/($small.height()-$mask.height())
		
	$bigimg.css({"margin-left":-bigimgMoveXX,"margin-top":-bigimgMoveYY})	
	})
	
})

其效果图如下:

好啦,今天的分享就到这啦,今天是元气满满的一天,加油!

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值