新建组件 -- Enlarge.vue
<template>
<transition
name="fade"
mode="out-in">
<div
v-show="url"
class="area"
:style="{
left: `${x}px`,
top: `${y}px`
}">
<img
:src="url"
:style="{
left: `${left}px`,
top: `${top}px`,
width,
height
}" >
</div>
</transition>
</template>
<script>
export default {
data () {
return {
target: null,
url: null,
width: 'auto',
height: 'auto',
left: 0,
top: 0,
x: 0,
y: 0
}
},
props: {
scale: {
type: Number,
default: 2
}
},
methods: {
enter(e = {}){
let { target } = e;
if(!target) return;
this.target = target;
this.target.addEventListener('mousemove', this.move);
this.target.addEventListener('mouseleave', this.leave);
this.url = target.getAttribute('src');
this.width = `${target.offsetWidth * this.scale}px`;
this.height = `${target.offsetHeight * this.scale}px`;
//预览放大图片的位置
let rect = target.getBoundingClientRect();
this.x = rect.left + target.offsetWidth + 20;
this.y = rect.top;
},
move(e){
let { offsetX, offsetY } = e;
this.left = -(offsetX * this.scale - (this.target.offsetWidth / 2));
this.top = -(offsetY * this.scale - (this.target.offsetHeight / 2));
},
leave(){
this.target.removeEventListener('mousemove', this.move);
this.url = null;
}
}
}
</script>
<style lang="scss" scoped>
.area{
width: 495px;
height: 495px;
position: fixed;
z-index: 100;
overflow: hidden;
background-color: #FFF;
border: 1px solid #aaa;
img{
position: absolute;
object-fit: contain;
}
}
.fade-leave-active,
.fade-enter-active {
transition: all 0.3s;
opacity: 1;
}
.fade-enter {
opacity: 0;
}
.fade-leave-to {
opacity: 0;
}
</style>
在需要使用的地方引入,并且调用
<template>
<div>
<img
src="/static/img/xxx.jpg"
@mouseenter="$refs.enlargeRef.enter($event)" />
<Enlarge
ref="enlargeRef" />
</div>
</template>
<script>
import Enlarge from '@/components/Enlarge.vue'
export default {
components: {
Enlarge
}
}
</script>