用到的技术
html + css + javascript + vue3.x + less
组件参数
参数 | 说明 |
---|---|
picSize | 图片尺寸 |
magnifierSize | 放大镜尺寸 |
magnifierNum | 放大倍数 |
效果展示
代码实现
<template>
<div class="demo">
<div
class="smallPic"
:style="{width: `${picSize}px`, height: `${picSize}px`}"
@mousemove="e=>moveOnImg(e)"
@mouseenter="mouseEnterLeaveImg(true)"
@mouseleave="mouseEnterLeaveImg(false)"
>
<img :src="src" />
<div
class="magnifier"
v-show="mouseIsOnImgOrNot"
:style="{width: `${magnifierSize}px`, height: `${magnifierSize}px`, left: `${magnifierX}px`, top: `${magnifierY}px`}"
>
<img
:src="src"
:style="{width: `${magnifierNum*picSize}px`, transform: `translate(${bigPicX}px, ${bigPicY}px)`}"
/>
</div>
</div>
</div>
</template>
<script>
import { reactive, toRefs, onMounted } from 'vue';
export default {
props: {
src: {
type: String,
default: require('../assets/tiankong.jpg'),
},
picSize: {
type: Number,
default: 400,
},
magnifierSize: {
type: Number,
default: 200,
},
magnifierNum: {
type: Number,
default: 2,
},
},
components: {},
setup(props) {
const state = reactive({
mouseOffsetX: 0,
mouseOffsetY: 0, // 鼠标相对于图片左上角的坐标位置
mouseIsOnImgOrNot: false, // 鼠标是否在图片上
magnifierX: 0,
magnifierY: 0, // 放大镜左上角位置
bigPicX: 0,
bigPicY: 0, // 放大镜中大图片的偏移位置
});
onMounted(() => {});
const moveOnImg = (e) => {
let event = e || window.event;
state.mouseOffsetX = event.offsetX;
state.mouseOffsetY = event.offsetY;
state.magnifierX = state.mouseOffsetX - props.magnifierSize / 2;
state.magnifierY = state.mouseOffsetY - props.magnifierSize / 2;
state.bigPicX = state.mouseOffsetX * props.magnifierNum * -1 + props.magnifierSize / 2;
state.bigPicY = state.mouseOffsetY * props.magnifierNum * -1 + props.magnifierSize / 2;
};
const mouseEnterLeaveImg = (val) => {
state.mouseIsOnImgOrNot = val;
};
return {
...toRefs(state),
moveOnImg,
mouseEnterLeaveImg,
};
},
};
//#333333
</script>
<style lang="less" scoped>
.demo {
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
.smallPic {
overflow: hidden;
position: relative;
z-index: 0;
img {
width: 100%;
}
&:hover {
cursor: crosshair;
}
.magnifier {
box-shadow: 0px 0px 6px rgb(0, 0, 0, 0.2);
border-radius: 10px;
position: absolute;
pointer-events: none;
overflow: hidden;
z-index: 1;
img {
pointer-events: none;
}
}
}
}
</style>