jQuery----使用jQuery实现放大镜的效果

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
    #div{width: 171px;height: 256px;padding: 5px;border: 1px solid #ccc;position: relative;}
    #div .small{width: 171px;height: 256px;background:         #eee;position: relative;}
    #div .float{width: 50px;height: 50px;border: 1px solid #000;background: #fff;filter: alpha(opacity: 30);opacity: 0.3;position: absolute;top: 0;left: 0;display: none;}
    #div .mark{width: 100%;height: 100%;position: absolute;z-index: 2;left: 0px;top: 0px;background: red;filter: alpha(opacity: 0);opacity: 0;}
    #div .big{position: absolute;top: -1px;left: 215px;width: 171px;height: 256px;overflow: hidden;border: 2px solid #CCC;display: none;}
    #div .big img {position: absolute;top: -30px;left: -80px;}
</style>
</head>
<body>
<!--用jquery面向对象写一个放大镜 -->
<!--注意:布局并设置好样式:大盒子div和小图盒子small为相对定位,遮罩mark滑块float大图盒子big大图图片均绝对定位,大图盒子big隐藏-->
<div id="div">
  <div class="small">
    <span class="mark"></span>
    <span class="float"></span>
    <img src="small.jpg" />
  </div>
  <div class="big">
    <img src="big.jpg" />
  </div>
</div>
</body>
</html>

js部分:

<script src="jquery-1.11.3.js"></script>
<script>
//jquery-1.11.3.js文件下载到本地并先导入该文件
//遮罩移入事件:滑块和大图盒子显示;遮罩移出事件:滑块和大图盒子隐藏;遮罩移动事件

$(function(){
  $('.mark').mouseenter(function(){
    $('.float').css({display: 'block'});
    $('.big').css({display: 'block'});
  }).mouseleave(function(){
    $('.float').css({display: 'none'});
    $('.big').css({display: 'none'});
  }).mousemove(function(e){
    //获取并设置滑块的位置
    var left = e.offsetX - $('.float').width() / 2;
    var top = e.offsetY - $('.float').height() / 2;

    //设置滑块边界
    if(left <= 0){
      left = 0;
    }else if(left >= $(this).outerWidth() - $('.float').outerWidth()){
      left = $(this).outerWidth() - $('.float').outerWidth();
    }
    if(top <= 0){
      top = 0;
    }else if(top >= $(this).outerHeight() - $('.float').outerHeight()){
      top = $(this).outerHeight() - $('.float').outerHeight();
    }
    $('.float').css({left:left + 'px',top:top + 'px'});
    //设置滑块在遮罩上的移动比例(当前所在位置 /(遮罩的宽 -滑块的宽))
    var pX = left / ($(this).outerHeight() - $('.float').outerHeight());
    var pY = top / ($(this).outerHeight() - $('.float').outerHeight());
    //依据比例来设置大图图片显示的位置
    var bigLeft = - pX * ($('.big img').outerWidth() - $('.big').outerWidth()) + 'px';
    var bigTop = - pY * ($('.big img').outerHeight() - $('.big').outerHeight()) + 'px';
    $('.big img').css({left:bigLeft,top:bigTop});
  })
})
</script>

 

posted @ 2019-01-07 12:22  snowstorm_22  阅读(276)  评论(0编辑  收藏  举报