放大镜效果是一种常见的前端交互效果,通常用于电商网站的商品展示或图片查看器中。它允许用户通过鼠标悬停在图片上时,显示一个放大的视图,以便更详细地查看图片的特定部分。
放大镜效果主要依赖于以下几个基础概念:
以下是一个简单的实现示例:
<div class="magnifier">
<img src="path/to/image.jpg" alt="Image" id="magnifier-image">
<div class="magnifier-lens" id="magnifier-lens"></div>
<div class="magnifier-result" id="magnifier-result"></div>
</div>
.magnifier {
position: relative;
display: inline-block;
}
.magnifier-lens {
position: absolute;
width: 100px;
height: 100px;
background-color: rgba(255, 255, 255, 0.5);
border: 1px solid #ccc;
pointer-events: none;
display: none;
}
.magnifier-result {
position: absolute;
top: 0;
left: 100%;
width: 300px;
height: 300px;
border: 1px solid #ccc;
overflow: hidden;
display: none;
}
document.addEventListener('DOMContentLoaded', function() {
const image = document.getElementById('magnifier-image');
const lens = document.getElementById('magnifier-lens');
const result = document.getElementById('magnifier-result');
const cx = result.offsetWidth / lens.offsetWidth;
const cy = result.offsetHeight / lens.offsetHeight;
image.addEventListener('mousemove', moveLens);
lens.addEventListener('mousemove', moveLens);
function moveLens(e) {
e.preventDefault();
const pos = getCursorPos(e);
let x = pos.x - (lens.offsetWidth / 2);
let y = pos.y - (lens.offsetHeight / 2);
if (x > image.width - lens.offsetWidth) {
x = image.width - lens.offsetWidth;
}
if (x < 0) {
x = 0;
}
if (y > image.height - lens.offsetHeight) {
y = image.height - lens.offsetHeight;
}
if (y < 0) {
y = 0;
}
lens.style.left = x + 'px';
lens.style.top = y + 'px';
result.style.backgroundPosition = `-${x * cx}px -${y * cy}px`;
}
function getCursorPos(e) {
let a = image.getBoundingClientRect();
return {
x: e.pageX - a.left - window.pageXOffset,
y: e.pageY - a.top - window.pageYOffset
};
}
image.addEventListener('mouseenter', () => {
lens.style.display = 'block';
result.style.display = 'block';
result.style.backgroundImage = `url(${image.src})`;
result.style.backgroundSize = `${image.width * cx}px ${image.height * cy}px`;
});
image.addEventListener('mouseleave', () => {
lens.style.display = 'none';
result.style.display = 'none';
});
});
position: relative
和position: absolute
的使用。requestAnimationFrame
优化性能。通过上述步骤和示例代码,你可以实现一个基本的放大镜效果。根据具体需求,还可以进一步优化和扩展功能。
领取专属 10元无门槛券
手把手带您无忧上云