css+js实现放大镜

155 阅读2分钟

思路

1.计算当前鼠标的位置,获取鼠标距离图片顶部和左边的距离  
镜子距离图片左边的距离=  鼠标到视口左边的距离-图片到左边的距离-镜子宽度的一半
镜子距离图片顶部的距离=  鼠标到视口顶部的距离-图片到顶部的距离-镜子高度的一半

2.将放大镜的topleft改成计算出来的数据,就能实现放大镜随着鼠标走
3.获取大图和小图的比例乘以距离+禁止的一半宽高,将放大的镜头放在中间就能实现放大镜同步       放大了
4.最后做一下限制,放大镜不能出界以及鼠标离开放大镜消失就完成整个功能了

备注:我这个是把放大镜放在图片里面,所有放大镜和原图看起来有一点错位的感觉,可以把放大镜放在图的旁边,就可以看到图片放大的地方就是鼠标悬浮的地方

代码

  <style>
    * {
      padding: 0;
      margin: 0;
    }
    body {
      width: 100vw;
      height: 100vh;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .box {
      width: 400px;
      position: relative;
    }
    .mirror {
      width: 150px;
      height: 150px;
      border-radius: 50%;
      border: 4px solid #000;
      overflow: hidden;
      position: absolute;
      top: 0;
      left: 0;
    }
    .mirror img {
      position: absolute;
    }
  </style>
  <body>
    <div class="box">
      <img src="https://img.huanhaoba.com/common/5eff4197-ddbd-4479-8196-249d9346f182.jpg" alt="" width="100%" />
      <div class="mirror">
        <img src="https://img.huanhaoba.com/common/5eff4197-ddbd-4479-8196-249d9346f182.jpg" alt="" />
      </div>
    </div>
  </body>
</html>
<script>
//获取照片盒子
  const box = document.querySelector(".box");
  const mirror = document.querySelector(".mirror");
  const bigImg = document.querySelector(".mirror img");

  box.addEventListener("mousemove", (e) => {
    // 获取鼠标相对于当前视口的距离
    let mLeft = e.clientX - box.offsetLeft - mirror.offsetWidth / 2;
    let mTop = e.clientY - box.offsetTop - mirror.offsetHeight / 2;
    // 计算最大值
    // 放大镜左边距离照片的宽度的最大值是照片的宽度-放大镜的宽度
    // 放大镜顶部到照片顶部的高度的最大值就是照片的高度-放大镜的高度
    let max_left = box.offsetWidth - mirror.offsetWidth;
    let max_Top = box.offsetHeight - mirror.offsetHeight;

    if (mLeft < 0) {
      mLeft = 0;
    }

    if (mLeft > max_left) {
      mLeft = max_left;
    }
    if (mTop < 0) {
      mTop = 0;
    }
    if (mTop > max_Top) {
      mTop = max_Top;
    }

    mirror.style.left = mLeft + "px";
    mirror.style.top = mTop + "px";

    bigImg.style.left =
      -(
        (bigImg.offsetWidth / box.offsetWidth) * mLeft +
        mirror.offsetWidth / 2
      ) + "px";

    bigImg.style.top =
      -(
        (bigImg.offsetHeight / box.offsetHeight) * mTop +
        mirror.offsetHeight / 2
      ) + "px";
  });
  box.addEventListener("mouseout", (e) => {
    mirror.style.visibility = "hidden";
  });
  box.addEventListener("mouseover", (e) => {
    mirror.style.visibility = "visible";
  });
</script>