淘宝的放大镜效果是一种常见的前端交互设计,用于在用户鼠标悬停在商品图片上时显示该商品的细节放大视图。以下是实现这一效果的基础概念和步骤:
<div class="magnifier">
<div class="small-box">
<img src="small.jpg" alt="Small Image" id="smallImage">
<div class="lens"></div>
</div>
<div class="large-box">
<img src="large.jpg" alt="Large Image" id="largeImage">
</div>
</div>
.magnifier {
position: relative;
display: inline-block;
}
.small-box {
position: relative;
overflow: hidden;
}
.small-box img {
width: 100%;
}
.lens {
position: absolute;
width: 100px; /* 放大镜宽度 */
height: 100px; /* 放大镜高度 */
background-color: rgba(255, 255, 255, 0.4);
cursor: none;
display: none;
}
.large-box {
position: absolute;
top: 0;
right: -100%; /* 放大镜图片位于小图右侧 */
width: 300px; /* 放大镜图片宽度 */
height: 300px; /* 放大镜图片高度 */
overflow: hidden;
}
.large-box img {
position: absolute;
width: auto;
height: auto;
}
document.addEventListener('DOMContentLoaded', function() {
const smallImage = document.getElementById('smallImage');
const largeImage = document.getElementById('largeImage');
const lens = document.querySelector('.lens');
smallImage.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 > smallImage.width - lens.offsetWidth) {
x = smallImage.width - lens.offsetWidth;
}
if (x < 0) {
x = 0;
}
if (y > smallImage.height - lens.offsetHeight) {
y = smallImage.height - lens.offsetHeight;
}
if (y < 0) {
y = 0;
}
lens.style.left = x + 'px';
lens.style.top = y + 'px';
largeImage.style.transform = `translate(-${x * 3}px, -${y * 3}px)`; // 假设放大倍数为3
}
function getCursorPos(e) {
let a = smallImage.getBoundingClientRect();
return {
x: e.pageX - a.left - window.pageXOffset,
y: e.pageY - a.top - window.pageYOffset
};
}
smallImage.addEventListener('mouseenter', () => {
lens.style.display = 'block';
});
smallImage.addEventListener('mouseleave', () => {
lens.style.display = 'none';
});
});
通过以上步骤和代码示例,可以实现一个基本的淘宝放大镜效果。根据实际需求,还可以进一步优化和扩展功能。
没有搜到相关的沙龙