CSS + JS 实现仿淘宝详情页放大镜

108 阅读1分钟

在许多电商网站,如淘宝,商品详情页通常会有一个放大镜效果,允许用户放大查看商品图片的细节。以下是一个简单的示例,展示如何用 HTML、CSS 和 JavaScript 实现这一功能。

HTML 结构

<div class="zoom-container">
  <div class="small-box" id="small-box">
    <img src="your-image.jpg" id="small-image" alt="商品图片" />
    <div class="mask" id="mask"></div>
  </div>
  <div class="big-box" id="big-box">
    <img src="your-image.jpg" id="big-image" alt="商品图片放大" />
  </div>
</div>

CSS 样式

.zoom-container {
  display: flex;
  position: relative;
}

.small-box {
  position: relative;
  width: 300px;
  height: 300px;
}

.small-box img,
.big-box img {
  width: 100%;
  height: 100%;
}

.mask {
  position: absolute;
  width: 100px;
  height: 100px;
  background-color: rgba(0, 0, 0, 0.3);
  display: none;
}

.big-box {
  position: absolute;
  left: 310px;
  width: 300px;
  height: 300px;
  overflow: hidden;
  display: none;
}

.big-box img {
  position: absolute;
}

JavaScript 代码

document.addEventListener("DOMContentLoaded", function () {
  const smallBox = document.getElementById("small-box");
  const bigBox = document.getElementById("big-box");
  const mask = document.getElementById("mask");
  const bigImage = document.getElementById("big-image");

  smallBox.addEventListener("mousemove", function (e) {
    const x = e.clientX - smallBox.getBoundingClientRect().left - mask.offsetWidth / 2;
    const y = e.clientY - smallBox.getBoundingClientRect().top - mask.offsetHeight / 2;
    let maskX = Math.min(Math.max(0, x), smallBox.offsetWidth - mask.offsetWidth);
    let maskY = Math.min(Math.max(0, y), smallBox.offsetHeight - mask.offsetHeight);

    mask.style.left = maskX + "px";
    mask.style.top = maskY + "px";
    mask.style.display = "block";
    bigBox.style.display = "block";

    const scaleX = maskX / (smallBox.offsetWidth - mask.offsetWidth);
    const scaleY = maskY / (smallBox.offsetHeight - mask.offsetHeight);

    bigImage.style.left = -(bigBox.offsetWidth * scaleX) + "px";
    bigImage.style.top = -(bigBox.offsetHeight * scaleY) + "px";
  });

  smallBox.addEventListener("mouseleave", function () {
    mask.style.display = "none";
    bigBox.style.display = "none";
  });
});

在这个示例中,.zoom-container 是放大镜效果的容器,.small-box 是原始图像的容器,.big-box 是放大图像的容器,而 .mask 是覆盖在 .small-box 上的蒙版。

当鼠标在 .small-box 上移动时,.mask.big-box 将会显示,并根据鼠标的位置进行相应的移动和放大。当鼠标离开 .small-box 时,.mask.big-box 将会隐藏。

这是一个基础的示例,你可以根据需要进行进一步的定制和优化。