上一篇
html网页放大镜
- 行业动态
- 2025-04-24
- 4455
HTML网页放大镜通过CSS设覆盖层,JS监听鼠标事件,动态调整位置大小并控制透明度,实现放大镜
实现原理
HTML网页放大镜主要通过CSS定位与JavaScript事件监听实现,核心思路是将原始图片作为背景图,通过移动覆盖层(透镜)实时显示图片局部区域的放大效果。
基础结构
<div class="magnifier-container"> <div class="magnifier-lens"></div> </div>
样式设计
属性 | 说明 |
---|---|
position: relative | 容器相对定位,为透镜绝对定位提供参考 |
background-image | 设置原始图片作为容器背景 |
overflow: hidden | 隐藏超出容器的图片内容 |
width/height | 定义容器尺寸(如300x300px) |
background-size | 控制图片缩放比例(如background-size: 600px 600px ) |
.magnifier-container { position: relative; width: 300px; height: 300px; background-image: url('image.jpg'); background-size: 600px 600px; / 原始图片尺寸 / overflow: hidden; } .magnifier-lens { position: absolute; width: 100px; / 透镜尺寸 / height: 100px; border: 2px solid #000; border-radius: 50%; background-color: rgba(255,255,255,0.5); cursor: none; }
交互逻辑
监听鼠标移动
通过mousemove
事件获取鼠标坐标,计算透镜位置。背景定位计算
根据鼠标位置反推背景图显示区域,公式:let x = e.offsetX lensWidth / 2; // 透镜中心对齐鼠标 let y = e.offsetY lensHeight / 2; // 限制边界 x = Math.max(0, Math.min(x, containerWidth lensWidth)); y = Math.max(0, Math.min(y, containerHeight lensHeight)); // 背景定位(反向缩放) lens.style.backgroundPosition = `-${x scale}px -${y scale}px`;
完整代码示例
<!DOCTYPE html> <html lang="zh"> <head> <style> .magnifier-container { position: relative; width: 300px; height: 300px; background-image: url('image.jpg'); background-size: 600px 600px; / 原始图片尺寸 / overflow: hidden; } .magnifier-lens { position: absolute; width: 100px; height: 100px; border: 2px solid #000; border-radius: 50%; background-color: rgba(255,255,255,0.5); cursor: none; } </style> </head> <body> <div class="magnifier-container" id="magnifier"> <div class="magnifier-lens"></div> </div> <script> const container = document.getElementById('magnifier'); const lens = container.querySelector('.magnifier-lens'); const scale = 2; // 放大倍数 const lensWidth = lens.offsetWidth; const lensHeight = lens.offsetHeight; const containerWidth = container.offsetWidth; const containerHeight = container.offsetHeight; container.addEventListener('mousemove', (e) => { let x = e.offsetX lensWidth / 2; let y = e.offsetY lensHeight / 2; // 边界限制 x = Math.max(0, Math.min(x, containerWidth lensWidth)); y = Math.max(0, Math.min(y, containerHeight lensHeight)); // 更新透镜位置 lens.style.left = x + 'px'; lens.style.top = y + 'px'; // 计算背景定位(反向缩放) const bgX = -x scale; const bgY = -y scale; lens.style.backgroundImage = `url('image.jpg')`; lens.style.backgroundSize = `${containerWidth scale}px ${containerHeight scale}px`; lens.style.backgroundPosition = `${bgX}px ${bgY}px`; }); </script> </body> </html>
常见问题与优化
如何调整放大倍数?
- 解答:修改
scale
变量值(如scale = 3
),同时需同步调整background-size
为容器宽度 scale
,注意过大倍数可能导致模糊。
移动端如何适配?
- 解答:替换
mousemove
为touchmove
事件,并计算触摸点坐标:container.addEventListener('touchmove', (e) => { const touch = e.touches[0]; const x = touch.clientX container.offsetLeft lensWidth / 2; const y = touch.clientY container.offsetTop lensHeight / 2; // 后续逻辑同鼠标事件... });