放大镜效果是一种常见的前端交互效果,通常用于电商网站的产品展示或图片查看器中。下面是一个简单的放大镜效果的JavaScript代码示例,结合HTML和CSS来实现。
<!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-container">
<img src="your-image.jpg" alt="Image" id="magnifier-image">
<div id="magnifier-lens"></div>
<div id="magnifier-result"></div>
</div>
<script src="script.js"></script>
</body>
</html>
/* styles.css */
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f0f0f0;
}
.magnifier-container {
position: relative;
display: inline-block;
}
#magnifier-image {
width: 300px;
height: auto;
}
#magnifier-lens {
position: absolute;
border: 2px 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;
background-repeat: no-repeat;
}
// script.js
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);
image.addEventListener('mouseenter', showLens);
image.addEventListener('mouseleave', hideLens);
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
};
}
function showLens() {
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`;
}
function hideLens() {
lens.style.display = 'none';
result.style.display = 'none';
}
});
放大镜效果通过创建一个透明的“镜头”覆盖在原始图像上,并在旁边显示一个放大的视图来实现。用户移动鼠标时,“镜头”跟随鼠标移动,并实时更新放大视图中的显示区域。
通过上述代码和解释,你应该能够实现一个基本的放大镜效果,并理解其背后的原理和应用场景。
领取专属 10元无门槛券
手把手带您无忧上云