javaScript商品放大镜
时间: 2023-11-21 12:57:57 浏览: 100
以下是一个简单的JavaScript商品放大镜的实现方法:
1. HTML结构
```html
<div class="product-image">
<img src="product-image.jpg" alt="Product Image">
<div class="zoom-container"></div>
</div>
```
2. CSS样式
```css
.product-image {
position: relative;
width: 400px;
height: 400px;
}
.product-image img {
width: 100%;
height: 100%;
object-fit: cover;
}
.zoom-container {
position: absolute;
top: 0;
right: -400px;
width: 400px;
height: 400px;
border: 1px solid #ccc;
overflow: hidden;
display: none;
}
.zoom-container img {
position: absolute; top: 0;
left: 0;
width: 800px;
height: 800px;
}
```
3. JavaScript代码
```javascript
const productImage = document.querySelector('.product-image');
const zoomContainer = document.querySelector('.zoom-container');
const zoomImage = document.createElement('img');
zoomImage.src = 'product-image.jpg';
zoomContainer.appendChild(zoomImage);
productImage.addEventListener('mousemove', function(e) {
const x = e.pageX - this.offsetLeft;
const y = e.pageY - this.offsetTop;
const zoomX = x / this.offsetWidth * zoomImage.offsetWidth - zoomContainer.offsetWidth / 2;
const zoomY = y / this.offsetHeight * zoomImage.offsetHeight - zoomContainer.offsetHeight / 2;
zoomImage.style.transform = `translate(${-zoomX}px, ${-zoomY}px)`;
zoomContainer.style.display = 'block';
});
productImage.addEventListener('mouseleave', function() {
zoomContainer.style.display = 'none';
});
```
以上代码实现了一个简单的商品放大镜效果,当鼠标在商品图片上移动时,会在旁边显示一个放大的镜头,镜头中显示的是鼠标所在位置的放大图像。当鼠标离开商品图片时,放大镜头会消失。
阅读全文