Web 页面实现图片放大镜效果
Web 页面实现图片放大镜效果
下面是一个完整的示例代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>图片放大镜效果</title>
<style>
.container {
position: relative;
width: 400px;
margin: 20px auto;
}
.main-image {
width: 400px;
height: 400px;
position: relative;
border: 1px solid #ccc;
}
.magnifier {
position: absolute;
width: 100px;
height: 100px;
background: rgba(0, 0, 0, 0.3);
border: 1px solid #999;
cursor: none;
display: none;
}
.zoom-area {
position: absolute;
width: 300px;
height: 300px;
border: 1px solid #ccc;
left: 420px;
top: 0;
overflow: hidden;
display: none;
}
.zoom-image {
position: absolute;
width: 1200px; /* 放大倍数 = 3倍 (300/100) */
height: 1200px;
}
</style>
</head>
<body>
<div class="container">
<div class="main-image">
<img
src="https://via.placeholder.com/400"
alt="图片"
style="width: 100%; height: 100%;"
/>
<div class="magnifier"></div>
</div>
<div class="zoom-area">
<img
class="zoom-image"
src="https://via.placeholder.com/1200"
alt="放大图片"
/>
</div>
</div>
<script>
const mainImage = document.querySelector(".main-image");
const magnifier = document.querySelector(".magnifier");
const zoomArea = document.querySelector(".zoom-area");
const zoomImage = document.querySelector(".zoom-image");
const magnifierSize = 100; // 放大镜尺寸
const zoomRatio = 3; // 放大倍数
mainImage.addEventListener("mouseenter", () => {
magnifier.style.display = "block";
zoomArea.style.display = "block";
});
mainImage.addEventListener("mouseleave", () => {
magnifier.style.display = "none";
zoomArea.style.display = "none";
});
mainImage.addEventListener("mousemove", (e) => {
// 获取图片的边界
const rect = mainImage.getBoundingClientRect();
// 计算鼠标在图片中的相对位置
let x = e.clientX - rect.left;
let y = e.clientY - rect.top;
// 限制放大镜位置不超过图片边界
x = Math.max(
magnifierSize / 2,
Math.min(x, rect.width - magnifierSize / 2)
);
y = Math.max(
magnifierSize / 2,
Math.min(y, rect.height - magnifierSize / 2)
);
// 设置放大镜位置
magnifier.style.left = x - magnifierSize / 2 + "px";
magnifier.style.top = y - magnifierSize / 2 + "px";
// 计算并设置放大图片的位置
const zoomX = (x - magnifierSize / 2) * zoomRatio;
const zoomY = (y - magnifierSize / 2) * zoomRatio;
zoomImage.style.left = -zoomX + "px";
zoomImage.style.top = -zoomY + "px";
});
</script>
</body>
</html>
这个示例实现了以下功能:
-
主要组件:
- 一个 400x400px 的主图片区域
- 一个 100x100px 的跟随鼠标移动的放大镜
- 一个 300x300px 的放大显示区域(放大 3 倍)
-
工作原理:
- 鼠标进入图片时显示放大镜和放大区域
- 鼠标离开图片时隐藏放大镜和放大区域
- 鼠标移动时:
- 放大镜跟随鼠标移动,始终以鼠标为中心
- 放大区域显示对应位置的放大内容
- 放大镜不会超出图片边界
-
使用说明:
- 将示例中的图片 URL(
https://via.placeholder.com/400和https://via.placeholder.com/1200)替换为实际的图片 - 注意:需要准备两张图片,一张正常尺寸(400x400),一张大尺寸(1200x1200)
- 大图尺寸应该是小图尺寸乘以放大倍数(这里是 3 倍)
- 将示例中的图片 URL(
-
可自定义参数:
.main-image的宽高:调整主图片大小.magnifier的宽高:调整放大镜大小.zoom-area的宽高:调整放大区域大小zoomRatio变量:调整放大倍数

Web 页面实现图片放大镜效果
浙公网安备 33010602011771号