淘宝的放大镜效果是一种常见的前端交互效果,用于在用户鼠标悬停在商品图片上时,显示一个放大的视图。这种效果通常通过HTML、CSS和JavaScript来实现。以下是一个简单的示例代码,展示了如何实现这种效果:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>放大镜效果</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="magnifier">
<img src="small.jpg" alt="商品图片" id="smallImage">
<div class="magnifier-lens" id="lens"></div>
<div class="magnifier-result" id="result"></div>
</div>
<script src="script.js"></script>
</body>
</html>
/* styles.css */
.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.5);
pointer-events: none;
display: none;
}
.magnifier-result {
position: absolute;
top: 0;
left: 100%;
width: 300px;
height: 300px;
border: 1px solid #000;
overflow: hidden;
display: none;
}
// script.js
document.addEventListener('DOMContentLoaded', function() {
const smallImage = document.getElementById('smallImage');
const lens = document.getElementById('lens');
const result = document.getElementById('result');
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';
result.style.backgroundPosition = `-${x * 3}px -${y * 3}px`;
}
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';
result.style.display = 'block';
result.style.backgroundImage = `url(${smallImage.src})`;
result.style.backgroundSize = `${smallImage.width * 3}px ${smallImage.height * 3}px`;
});
smallImage.addEventListener('mouseleave', () => {
lens.style.display = 'none';
result.style.display = 'none';
});
});
.magnifier-lens
和.magnifier-result
的display
属性是否正确设置。通过以上代码和解释,你应该能够理解并实现一个基本的淘宝放大镜效果。如果有更多具体问题,欢迎进一步探讨。
没有搜到相关的文章