Web开发 —— 放大镜效果(HTML、CSS、JavaScript)
以下是实现放大镜效果的简单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>
<style>
.magnifier {
position: relative;
width: 150px;
height: 150px;
overflow: hidden;
float: left;
margin-right: 20px;
}
.magnifier img {
width: 150px;
height: 150px;
}
.magnifier-large {
position: absolute;
width: 300px;
height: 300px;
background-color: rgba(255, 255, 0, 0.5);
display: none;
top: 0;
left: 150px;
cursor: none;
overflow: hidden;
}
.magnifier-large img {
position: absolute;
width: 600px;
height: auto;
}
</style>
</head>
<body>
<div class="magnifier" id="magnifier1">
<img src="small-image.jpg" alt="小图片">
<div class="magnifier-large">
<img src="large-image.jpg" alt="大图片">
</div>
</div>
<script>
function createMagnifier(magnifier) {
const magnifierLarge = magnifier.querySelector('.magnifier-large');
const ratio = 3; // 放大倍数
const img = magnifierLarge.querySelector('img');
// 鼠标移入放大镜区域时显示放大镜
magnifier.addEventListener('mouseenter', function(e) {
magnifierLarge.style.display = 'block';
});
// 鼠标移出放大镜区域时隐藏放大镜
magnifier.addEventListener('mouseleave', function(e) {
magnifierLarge.style.display = 'none';
});
// 鼠标移动时更新放大镜的位置
magnifier.addEventListener('mousemove', function(e) {
const x = e.pageX - magnifier.offsetLeft - magnifierLarge.offsetWidth / 2;
const y = e.pageY - magnifier.offsetTop - magnifierLarge.offsetHeight / 2;
const maxX = img.offsetWidth - magnifierLarge.offsetWidth;
const maxY = img.offsetHeight - magnifierLarge.offsetHeight;
// 限制放大镜的移动范围
if (x < 0) {
x = 0;
} else if (x > maxX) {
x = maxX;
}
if (y < 0) {
y = 0;
} else if (y > maxY) {
y = maxY;
}
// 更新放大镜位置
magnifierLarge.style.left = x + 'px';
magnifierLarge.style.top = y + 'px';
// 更新大图显示区域
img.style.left = -x * ratio + 'px';
img.style.top = -y * ratio + 'px';
});
}
// 初始化放大镜效果
document.querySelectorAll('.magnifier').forEach(createMagnifier);
</script>
</body>
</html>
这段代码中,.magnifier
是放大镜容器,\`.m
评论已关闭