vue实现放大镜
Vue 实现放大镜效果
基本原理
放大镜效果通常通过监听鼠标移动事件,动态计算放大区域并显示放大后的图像。核心逻辑包括获取鼠标位置、计算放大比例、显示放大区域。

实现步骤
HTML 结构

<template>
<div class="magnifier-container">
<div class="original-image" @mousemove="handleMouseMove" @mouseleave="handleMouseLeave">
<img :src="imageUrl" ref="originalImage">
<div class="zoom-lens" v-show="showLens" :style="lensStyle"></div>
</div>
<div class="zoomed-image" v-show="showZoom" :style="zoomStyle"></div>
</div>
</template>
CSS 样式
.magnifier-container {
position: relative;
display: flex;
}
.original-image {
position: relative;
cursor: zoom-in;
}
.zoom-lens {
position: absolute;
border: 1px solid #ddd;
background-color: rgba(255, 255, 255, 0.3);
pointer-events: none;
}
.zoomed-image {
margin-left: 20px;
background-repeat: no-repeat;
border: 1px solid #ddd;
}
JavaScript 逻辑
<script>
export default {
props: {
imageUrl: String,
zoomScale: {
type: Number,
default: 2
},
lensSize: {
type: Number,
default: 100
}
},
data() {
return {
showLens: false,
showZoom: false,
lensStyle: {},
zoomStyle: {}
}
},
methods: {
handleMouseMove(e) {
const originalImg = this.$refs.originalImage;
const containerRect = originalImg.getBoundingClientRect();
// 计算镜头位置
let x = e.pageX - containerRect.left - window.pageXOffset - this.lensSize / 2;
let y = e.pageY - containerRect.top - window.pageYOffset - this.lensSize / 2;
// 限制镜头不超出图像范围
x = Math.max(0, Math.min(x, originalImg.width - this.lensSize));
y = Math.max(0, Math.min(y, originalImg.height - this.lensSize));
this.lensStyle = {
width: `${this.lensSize}px`,
height: `${this.lensSize}px`,
left: `${x}px`,
top: `${y}px`
};
// 计算放大区域
this.zoomStyle = {
width: `${originalImg.width}px`,
height: `${originalImg.height}px`,
backgroundImage: `url(${this.imageUrl})`,
backgroundSize: `${originalImg.width * this.zoomScale}px ${originalImg.height * this.zoomScale}px`,
backgroundPosition: `-${x * this.zoomScale}px -${y * this.zoomScale}px`
};
this.showLens = true;
this.showZoom = true;
},
handleMouseLeave() {
this.showLens = false;
this.showZoom = false;
}
}
}
</script>
使用示例
<template>
<Magnifier
imageUrl="/path/to/image.jpg"
:zoomScale="3"
:lensSize="150"
/>
</template>
注意事项
- 确保原始图像已完全加载后再进行放大操作,可在
mounted钩子中添加加载监听 - 对于响应式设计,需要监听窗口大小变化并重新计算位置
- 移动端支持需要添加触摸事件处理
- 性能优化可以考虑使用
transform替代background-position






