今天给大家实现放大镜的功能,也就是平时商城会经常用到的一种效果,其方法是,准备一张高像素的大图,当鼠标放到小图上,通过对大图进行绝对定位以此加载显示对应的位置,并且用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})
})
})
其效果图如下:
好啦,今天的分享就到这啦,今天是元气满满的一天,加油!