淘宝图片放大镜是一种常见的前端交互效果,允许用户在查看商品图片时,通过鼠标悬停或点击某个区域来放大显示图片的特定部分。这种效果通常通过JavaScript和CSS实现,结合HTML结构来完成。
以下是一个简单的基于鼠标悬停的淘宝图片放大镜实现示例:
<div class="magnifier">
<img src="small.jpg" alt="Small Image" id="smallImage">
<div class="magnifier-lens"></div>
<div class="magnifier-result"></div>
</div>
.magnifier {
position: relative;
display: inline-block;
}
.magnifier-lens {
position: absolute;
border: 1px solid #000;
width: 100px;
height: 100px;
background-color: rgba(255, 255, 255, 0.4);
cursor: none;
}
.magnifier-result {
position: absolute;
top: 0;
right: -300px; /* Adjust as needed */
width: 300px;
height: 300px;
border: 1px solid #000;
overflow: hidden;
display: none;
}
document.addEventListener('DOMContentLoaded', function() {
const smallImage = document.getElementById('smallImage');
const lens = document.querySelector('.magnifier-lens');
const result = document.querySelector('.magnifier-result');
smallImage.addEventListener('mousemove', moveLens);
lens.addEventListener('mousemove', moveLens);
function moveLens(e) {
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';
result.style.backgroundPosition = `-${x * 3}px -${y * 3}px`; // Adjust the multiplier as needed
}
smallImage.addEventListener('mouseenter', showLens);
smallImage.addEventListener('mouseleave', hideLens);
function showLens() {
lens.style.display = 'block';
result.style.display = 'block';
result.style.backgroundImage = `url(${smallImage.src})`;
result.style.backgroundSize = `${smallImage.width * 3}px ${smallImage.height * 3}px`; // Adjust the multiplier as needed
}
function hideLens() {
lens.style.display = 'none';
result.style.display = 'none';
}
function getCursorPos(e) {
let a = smallImage.getBoundingClientRect();
return {
x: e.pageX - a.left - window.pageXOffset,
y: e.pageY - a.top - window.pageYOffset
};
}
});
window.pageXOffset
和window.pageYOffset
。requestAnimationFrame
优化动画效果,减少不必要的DOM操作。通过以上方法,可以有效实现并优化淘宝图片放大镜效果,提升用户体验。
没有搜到相关的文章