JS+CSS+THML写出放大镜全效果
时间: 2023-06-28 07:16:12 浏览: 112
以下是一个基本的放大镜效果的HTML、CSS和JavaScript代码示例:
HTML代码:
```html
<div class="container">
<div class="image-zoom">
<img src="image.jpg" alt="Image">
<div class="zoom-overlay"></div>
</div>
</div>
```
CSS代码:
```css
.container {
max-width: 800px;
margin: 0 auto;
}
.image-zoom {
position: relative;
width: 400px;
height: 400px;
overflow: hidden;
}
.image-zoom img {
display: block;
max-width: 100%;
height: auto;
}
.zoom-overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: 0;
background: rgba(255, 255, 255, 0.5);
cursor: crosshair;
z-index: 1;
}
.zoom-overlay.active {
opacity: 1;
}
.zoom-overlay .zoom {
position: absolute;
top: 0;
left: 0;
width: 200px;
height: 200px;
border: 1px solid #ccc;
background: #fff;
background-image: url('image.jpg');
background-size: 800px 800px;
background-repeat: no-repeat;
background-position: 0 0;
z-index: 2;
pointer-events: none;
opacity: 0;
transition: opacity 0.2s;
}
.zoom-overlay.active .zoom {
opacity: 1;
}
```
JavaScript代码:
```javascript
const container = document.querySelector('.container');
const imageZoom = container.querySelector('.image-zoom');
const zoomOverlay = imageZoom.querySelector('.zoom-overlay');
const zoom = zoomOverlay.querySelector('.zoom');
imageZoom.addEventListener('mousemove', (e) => {
const { left, top, width, height } = imageZoom.getBoundingClientRect();
const x = e.clientX - left;
const y = e.clientY - top;
const offsetX = x / width * 100;
const offsetY = y / height * 100;
zoom.style.backgroundPosition = `${offsetX}% ${offsetY}%`;
zoom.style.left = `${x - 100}px`;
zoom.style.top = `${y - 100}px`;
});
imageZoom.addEventListener('mouseenter', () => {
zoomOverlay.classList.add('active');
});
imageZoom.addEventListener('mouseleave', () => {
zoomOverlay.classList.remove('active');
});
```
这段代码实现了一个基本的放大镜效果。当鼠标移动到图片上时,会在图片下方出现一个放大镜区域,同时在放大镜区域中显示鼠标所在位置的缩放图像。当鼠标移开图片时,放大镜区域会消失。你可以根据需要修改CSS和JavaScript代码来实现更复杂的放大镜效果。
阅读全文