固定尺寸的照片设置放大镜代码
时间: 2023-12-18 19:02:27 浏览: 17
以下是一个简单的示例代码,可以实现在固定尺寸的照片上设置放大镜:
```html
<!DOCTYPE html>
<html>
<head>
<title>商品放大镜</title>
<style>
/* 放大镜容器 */
.zoom {
position: relative;
width: 200px;
height: 200px;
margin: 50px auto;
overflow: hidden;
border: 1px solid #d4d4d4;
}
/* 放大镜 */
.zoom img {
position: absolute;
top: 0;
left: 0;
width: 400px; /* 放大后的图片宽度 */
height: 400px; /* 放大后的图片高度 */
display: none;
}
/* 鼠标跟随区域 */
.zoom-lens {
position: absolute;
width: 100px;
height: 100px;
border: 1px solid #d4d4d4;
opacity: 0.5;
}
</style>
</head>
<body>
<div class="zoom">
<img src="image.jpg" width="200" height="200" alt="商品图片">
<div class="zoom-lens"></div>
</div>
<script>
// 获取元素
var zoom = document.querySelector('.zoom');
var lens = document.querySelector('.zoom-lens');
var img = zoom.querySelector('img');
// 鼠标移动事件
zoom.addEventListener('mousemove', function(e) {
// 获取鼠标在放大镜容器中的位置
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
// 计算放大镜位置
var lensX = x - lens.offsetWidth / 2;
var lensY = y - lens.offsetHeight / 2;
// 限制放大镜的移动范围
if (lensX < 0) lensX = 0;
if (lensY < 0) lensY = 0;
if (lensX > zoom.offsetWidth - lens.offsetWidth) lensX = zoom.offsetWidth - lens.offsetWidth;
if (lensY > zoom.offsetHeight - lens.offsetHeight) lensY = zoom.offsetHeight - lens.offsetHeight;
// 设置放大镜位置
lens.style.left = lensX + 'px';
lens.style.top = lensY + 'px';
// 计算放大比例
var scale = img.offsetWidth / zoom.offsetWidth;
// 设置放大后的图片位置
img.style.left = -lensX * scale + 'px';
img.style.top = -lensY * scale + 'px';
img.style.display = 'block';
});
// 鼠标移出事件
zoom.addEventListener('mouseout', function() {
img.style.display = 'none';
});
</script>
</body>
</html>
```
需要注意的是,代码中的图片路径需要根据实际情况进行修改。