原生HTML放大镜
要创建一个原生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>Image Magnifier</title>
<style>
.magnifier-wrapper {
position: relative;
width: 300px;
height: 300px;
overflow: hidden;
cursor: crosshair;
}
.magnifier-glass {
position: absolute;
border: 2px solid #000;
cursor: none;
background-color: #fff;
opacity: 0.5;
pointer-events: none;
}
.large-image {
width: 600px;
height: 600px;
display: none;
}
</style>
</head>
<body>
<div class="magnifier-wrapper">
<img src="small-image.jpg" alt="Magnified Image" class="large-image">
<div class="magnifier-glass"></div>
</div>
<script>
const wrapper = document.querySelector('.magnifier-wrapper');
const glass = document.querySelector('.magnifier-glass');
const largeImage = document.querySelector('.large-image');
wrapper.addEventListener('mousemove', (e) => {
const magnifierRadius = glass.offsetWidth / 2;
const smallImagePos = wrapper.getBoundingClientRect();
const largeImagePos = largeImage.getBoundingClientRect();
// Position magnifier glass over small image
glass.style.top = `${e.pageY - smallImagePos.top - magnifierRadius}px`;
glass.style.left = `${e.pageX - smallImagePos.left - magnifierRadius}px`;
// Show the large image
largeImage.style.display = 'block';
// Position the large image
const scaleFactor = largeImage.offsetWidth / wrapper.offsetWidth;
const x = (e.pageX - smallImagePos.left) * scaleFactor - magnifierRadius * scaleFactor;
const y = (e.pageY - smallImagePos.top) * scaleFactor - magnifierRadius * scaleFactor;
largeImage.style.backgroundPositionX = `${x}px`;
largeImage.style.backgroundPositionY = `${y}px`;
});
wrapper.addEventListener('mouseleave', () => {
largeImage.style.display = 'none';
});
</script>
</body>
</html>
在这个例子中,.magnifier-wrapper
是放大镜的容器,.magnifier-glass
是放大镜本身,而 .large-image
是一个背景图片,它是放大镜下方大图的容器。JavaScript 监听鼠标移动事件,计算放大镜的位置,并相应地调整大图的位置以模拟放大镜效果。鼠标离开放大镜区域时,大图隐藏。
请确保将 small-image.jpg
替换为你的实际图片路径。你可以通过调整 .magnifier-glass
的大小和 .large-image
的大小及其背景尺寸来改变放大镜的效果。
评论已关闭