帮我写个放大镜的html
时间: 2023-12-26 07:12:47 浏览: 63
<!DOCTYPE html>
<html>
<head>
<title>放大镜</title>
<style>
.container {
display: flex;
align-items: center;
justify-content: center;
margin-top: 50px;
}
.image-container {
position: relative;
margin-right: 20px;
}
.image {
width: 400px;
height: 400px;
object-fit: cover;
}
.zoom {
position: absolute;
width: 200px;
height: 200px;
border: 1px solid black;
display: none;
z-index: 100;
cursor: crosshair;
}
.zoom img {
position: absolute;
top: 0;
left: 0;
width: 800px;
height: 800px;
object-fit: cover;
}
</style>
</head>
<body>
<div class="container">
<div class="image-container">
<img class="image" src="https://images.unsplash.com/photo-1630008496466-99f6c7b8f2b0?ixid=MnwxMjA3fDB8MHxwcm9maWxlLXBhZ2V8MTB8fHxlbnwwfHx8fA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" alt="Image">
<div class="zoom"></div>
</div>
</div>
<script>
const imageContainer = document.querySelector('.image-container');
const image = document.querySelector('.image');
const zoom = document.querySelector('.zoom');
const zoomImg = document.createElement('img');
zoom.appendChild(zoomImg);
imageContainer.addEventListener('mouseenter', () => {
zoom.style.display = 'block';
});
imageContainer.addEventListener('mouseleave', () => {
zoom.style.display = 'none';
});
imageContainer.addEventListener('mousemove', e => {
const x = e.clientX - imageContainer.getBoundingClientRect().left;
const y = e.clientY - imageContainer.getBoundingClientRect().top;
const offsetX = x / imageContainer.offsetWidth * 100;
const offsetY = y / imageContainer.offsetHeight * 100;
zoom.style.left = `${x}px`;
zoom.style.top = `${y}px`;
zoomImg.style.left = `-${offsetX * 3}px`;
zoomImg.style.top = `-${offsetY * 3}px`;
});
zoomImg.src = image.src;
</script>
</body>
</html>
阅读全文