<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>图片放大镜效果</title>
<style>
body {
font-family: Arial, sans-serif;
display: flex;
flex-direction: column;
align-items: center;
padding: 20px;
background-color: #f5f5f5;
}
h1 {
color: #333;
margin-bottom: 30px;
}
.magnifier-container {
position: relative;
width: 500px;
height: 350px;
border: 1px solid #ddd;
overflow: hidden;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
.main-image {
width: 100%;
height: 100%;
object-fit: cover;
cursor: crosshair;
}
.magnifier {
position: absolute;
width: 150px;
height: 150px;
border: 3px solid #fff;
border-radius: 50%;
background-repeat: no-repeat;
pointer-events: none;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
display: none;
z-index: 10;
}
.instructions {
margin-top: 20px;
color: #666;
font-size: 14px;
}
.link {
margin-top: 30px;
color: #0066cc;
text-decoration: none;
}
.link:hover {
text-decoration: underline;
}
</style>
</head>
<body>
<h1>图片放大镜效果演示</h1>
<div class="magnifier-container">
<img src="https://images.unsplash.com/photo-1506744038136-46273834b3fb" alt="示例图片" class="main-image" id="mainImage">
<div class="magnifier" id="magnifier"></div>
</div>
<p class="instructions">将鼠标移动到图片上查看放大效果</p>
<script>
const mainImage = document.getElementById('mainImage');
const magnifier = document.getElementById('magnifier');
// 设置放大倍数
const zoomLevel = 2;
mainImage.addEventListener('mousemove', function(e) {
// 显示放大镜
magnifier.style.display = 'block';
// 获取鼠标在图片上的位置
const rect = mainImage.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
// 确保放大镜不会超出图片边界
const magnifierWidth = magnifier.offsetWidth;
const magnifierHeight = magnifier.offsetHeight;
let posX = x - magnifierWidth / 2;
let posY = y - magnifierHeight / 2;
// 边界检查
if (posX < 0) posX = 0;
if (posY < 0) posY = 0;
if (posX > rect.width - magnifierWidth) posX = rect.width - magnifierWidth;
if (posY > rect.height - magnifierHeight) posY = rect.height - magnifierHeight;
// 设置放大镜位置
magnifier.style.left = posX + 'px';
magnifier.style.top = posY + 'px';
// 计算放大镜背景位置
const bgX = -x * zoomLevel + magnifierWidth / 2;
const bgY = -y * zoomLevel + magnifierHeight / 2;
// 设置放大镜背景
magnifier.style.backgroundImage = `url('${mainImage.src}')`;
magnifier.style.backgroundSize = `${rect.width * zoomLevel}px ${rect.height * zoomLevel}px`;
magnifier.style.backgroundPosition = `${bgX}px ${bgY}px`;
});
mainImage.addEventListener('mouseleave', function() {
// 鼠标离开时隐藏放大镜
magnifier.style.display = 'none';
});
</script>
</body>
</html>
图片放大镜效果
于 2025-06-07 15:45:21 首次发布
634

被折叠的 条评论
为什么被折叠?



