如何用原生js实现放大镜特效

 

  <!DOCTYPE html>
  <html>
  <head>
  <meta charset="UTF-8">
  <title></title>
  <style type="text/css">
  #box{
  width: 1000px;
  height: 400px;
  border: 1px solid salmon;
  position: relative;
  margin: 50px auto;
  }
  #small{
  width: 350px;
  height: 350px;
  position: absolute;
  border: 1px solid slateblue;
  }
  #big{
  width: 350px;
  height: 350px;
  position: absolute;
  border: 1px solid slateblue;
  left: 352px;
  overflow: hidden;
  display: none;
  }
  #mark{
  width: 153px;
  height: 153px;
  background-color: rgba(0,0,0,0.5);
  position: absolute;
  display: none;
  }
  .limg{
  position: absolute;
  }
  </style>
  </head>
  <body>
  <div id="box">
  <div id="small">
  <div id="mark"></div>
  <img src="img/product-s4-m.jpg"/>
  </div>
  <div id="big">
  <img src="img/product-s4-l.jpg" class="limg" id="img2"/>
  </div>
  </div>
  </body>
  <script type="text/javascript">
   
  function demo(str){
  return str ? document.getElementById(str) : null;
  }
  var big = demo("big");
  var small = demo("small");
  var mark = demo("mark");
  var box = demo("box");
  small.onmouseover = function(){
  mark.style.display = "block";
  big.style.display = "block";
  }
  small.onmouseout = function(){
  mark.style.display = "none";
  big.style.display = "none";
  }
  small.onmousemove = function(eve){
  eve = window.event || eve;
  var x = eve.clientX - small.parentElement.offsetLeft - mark.clientWidth/2;
  var y = eve.clientY -small.parentElement.offsetTop - mark.clientHeight/2;
   
  //限制mark出框
  if (x<0) {
  x = 0;
  }
  if (y<0) {
  y = 0;
  }
  if (x > small.clientWidth-mark.clientWidth) {
  x = small.clientWidth-mark.clientWidth;
  }
  if (y > small.clientHeight - mark.clientHeight) {
  y = small.clientHeight - mark.clientHeight;
  }
   
  mark.style.left = x + "px";
  mark.style.top = y + "px";
  //获得比例
  var limg = document.getElementsByClassName("limg")[0];
  var img2 = document.getElementById("img2");
  console.log(limg.clientWidth);
  var scare = (limg.height - big.clientHeight)/(small.clientHeight - mark.clientHeight);
  limg.style.left = - x * scare + "px";
  limg.style.top = - y * scare + "px";
   
   
  }
   
  </script>
  </html>
   

 

 

 

posted on 2017-07-20 16:53  时光不染回忆不淡  阅读(121)  评论(0编辑  收藏  举报

导航