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

泄露秘密 提交于 2020-02-11 08:05:11

 

  <!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>
   

 

 

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!