jquery 放大镜
以下是实现 jQuery 放大镜效果的两种常见方法,适用于商品图片局部放大等场景:
基础实现方法
准备 HTML 结构,包含原图容器和放大镜显示区域:
<div class="container">
<img src="small.jpg" class="small-img">
<div class="zoom-lens"></div>
</div>
<div class="zoom-result"></div>
CSS 样式设置:

.zoom-lens {
position: absolute;
width: 100px;
height: 100px;
background: rgba(255, 255, 255, 0.3);
border: 1px solid #ccc;
cursor: none;
display: none;
}
.zoom-result {
position: absolute;
width: 400px;
height: 400px;
overflow: hidden;
display: none;
border: 1px solid #ddd;
}
jQuery 核心逻辑:
$(document).ready(function(){
$(".container").on("mousemove", function(e){
const lens = $(".zoom-lens");
const result = $(".zoom-result");
const smallImg = $(".small-img");
// 计算镜头位置
const x = e.pageX - $(this).offset().left - lens.width()/2;
const y = e.pageY - $(this).offset().top - lens.height()/2;
// 边界检查
const maxX = $(this).width() - lens.width();
const maxY = $(this).height() - lens.height();
lens.css({
left: Math.min(Math.max(0, x), maxX),
top: Math.min(Math.max(0, y), maxY),
display: "block"
});
// 计算放大比例
const ratioX = result.width() / lens.width();
const ratioY = result.height() / lens.height();
// 设置放大区域背景
result.css({
"background-image": "url('large.jpg')",
"background-size": smallImg.width() * ratioX + "px " + smallImg.height() * ratioY + "px",
"background-position": -x * ratioX + "px " + -y * ratioY + "px",
display: "block"
});
});
$(".container").on("mouseleave", function(){
$(".zoom-lens, .zoom-result").hide();
});
});
使用插件简化实现
引入 jQuery Zoom 插件(需先加载 jQuery):

<script src="https://cdn.jsdelivr.net/npm/jquery-zoom@1.7.21/jquery.zoom.min.js"></script>
初始化插件:
$('.small-img').zoom({
url: 'large.jpg', // 大图路径
magnify: 2, // 放大倍数
on: 'hover' // 触发方式
});
插件配置选项:
target:指定放大镜显示容器touch:启用触摸屏支持(默认 true)duration:动画持续时间(毫秒)onZoomIn/onZoomOut:回调函数
注意事项
- 大图尺寸建议至少是原图的 2 倍以上以保证清晰度
- 移动端适配需要添加触摸事件支持
- 性能优化建议对大图进行预加载
- 复杂场景可考虑使用 WebGL 实现更流畅的放大效果
两种方法各有优势:基础实现更灵活可控,插件方案开发效率更高。实际选择应根据项目需求和性能要求决定。






