实现一个vue放大镜功能完整代码
以下是一个Vue的放大镜组件的完整代码:
<template>
<div class="magnifier-container">
<div class="magnifier-wrapper">
<div class="magnifier-image-wrapper">
<img
class="magnifier-image"
:src="imageSrc"
:style="{ transform: 'scale(' + scale + ')', left: -left + 'px', top: -top + 'px' }"
@mousemove="handleMouseMove"
@mouseenter="handleMouseEnter"
@mouseleave="handleMouseLeave"
/>
</div>
<div class="magnifier-glass" :style="{ width: size + 'px', height: size + 'px' }"></div>
</div>
</div>
</template>
<script>
export default {
props: {
imageSrc: {
type: String,
required: true,
},
size: {
type: Number,
default: 200,
},
scale: {
type: Number,
default: 2,
},
},
data() {
return {
left: 0,
top: 0,
showMagnifier: false,
};
},
methods: {
handleMouseMove(event) {
if (this.showMagnifier) {
const { left, top } = event.target.getBoundingClientRect();
const x = event.clientX - left;
const y = event.clientY - top;
const halfSize = this.size / 2;
const maxX = event.target.clientWidth - halfSize;
const maxY = event.target.clientHeight - halfSize;
this.left = Math.min(Math.max(x - halfSize, 0), maxX);
this.top = Math.min(Math.max(y - halfSize, 0), maxY);
}
},
handleMouseEnter() {
this.showMagnifier = true;
},
handleMouseLeave() {
this.showMagnifier = false;
},
},
};
</script>
<style scoped>
.magnifier-container {
position: relative;
}
.magnifier-wrapper {
position: relative;
display: inline-block;
}
.magnifier-image-wrapper {
overflow: hidden;
position: relative;
display: inline-block;
}
.magnifier-image {
display: block;
position: absolute;
transition: transform 0.1s linear;
}
.magnifier-glass {
position: absolute;
top: 0;
left: 0;
pointer-events: none;
border-radius: 50%;
background-color: rgba(255, 255, 255, 0.3);
transform: translate(-50%, -50%);
box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.3);
z-index: 999;
transition: opacity 0.1s linear;
opacity: 0;
}
.magnifier-wrapper:hover .magnifier-glass {
opacity: 1;
}
</style>
这个组件接受三个props:imageSrc表示要展示的图片的地址,size表示放大镜的直径,scale表示放大倍数。组件中的handleMouseMove方法根据鼠标的位置计算出放大镜在图片上的位置,handleMouseEnter和handleMouseLeave方法分别在鼠标移入和移出图片时控制放大镜的显示和隐藏。组件中的样式基本上都是用来控制放大镜的样式和位置的。
原文地址: https://www.cveoy.top/t/topic/btBs 著作权归作者所有。请勿转载和采集!