首页 > 代码库 > 随笔-放大镜效果

随笔-放大镜效果

<!doctype html>

<html>

<head>

<meta charset=‘utf-8‘>

<title>随笔-放大镜效果</title>

<style>

#box {
margin: 100px;
}
#small {
width: 250px;
height: 250px;
float: left;
border: 1px solid #ccc;
position: relative;
}
#mask {
width: 80px;
height: 80px;
background: rgba(0,0,0,.8);
position: absolute;
left: 0;
top: 0;
display: none;
}
#big {
width: 250px;
height: 250px;
overflow: hidden;
border: 1px solid #ccc;
float: left;
display: none;
}

</style>

</head>

<body>

  <script type="text/javascript">

     window.onload = function(){

        //创建一个函数方便获取各个 ID 

        function getId(id){

          return document.getElementById(id);

        }

        var box = getId(‘box‘);

        var samll = getId(‘small‘);

        var mask = getId(‘mask‘);

        var big = getId(‘big‘);

        var bigPic = big.children[0];

        //通过鼠标经过small,焦点框出现,展示图片也出现,相反鼠标移出都隐藏

        small.onmouseover = function(){

          mask.style.display = ‘block‘;

          big.style.display = ‘block‘;

        }

        small.onmouseout = function(){

          mask.style.display = ‘none‘;

          big.style.display = ‘none‘;

        }

        //鼠标移动  且鼠标在焦点框中心位置

        mask.onmousemove = function(e){

          var x = box.offsetLeft;             //获取装图片的盒子的真实位置

          var y = box.offsetTop;

          var currentX = e.clientX;            //获取鼠标的位置

          var currentY = e.clientY;

          var l = currentX - x - mask.offsetWidth/2;   //用鼠标位置减去图片盒子的位置得出small和mask的距离,再减去mask宽高的一半就到中心了

          var t = currentY - y -mask.offsetHeight/2;

          //限制焦点框只能在samll里面移动,不能超过small框外

          if(x < 0){x = 0}

          if(x > small.offsetWidth - mask.offsetWidth){

            x = small.offsetWidth - mask.offsetWidth;

          }

          if(y < 0){y = 0}

          if(y > small.offsetHeight - mask.offsetHeight){

            y = small.offsetHeight - mask.offsetHeight;

          }

          //放大镜展示 用 负的margin 值操作放大镜图片的位置

          var L = mask.offsetLeft;

          var T = mask.offsetTop;

          var Px = pic.offsetWidth/small.offsetWidth;    //计算两张图的一个比例,再根据焦点的移动乘以比例值来确定放大镜的图片的位置

          var Py = pic.offsetHeight/small.offsetHeight;

          pic.style.marginLeft = -L*Px + ‘px‘;        //用负的margin值来操作放大镜的图片

          pic.style.marginTopt = -T*Py + ‘px‘;

        }

     }

  </script>

  <div id="box">

    <div id="small">

      <img src="http://www.mamicode.com/pic.jpg" width="250" height="250">

      <div id="mask"></div>

    </small>

    <div id="big">

      <img src="http://www.mamicode.com/pic.jpg" width="500" height="500">

    </div>

  </div>

</body>

</html>

随笔-放大镜效果