使用步骤
1.引入相应的包
因为使用了less所以这一步不是必须的
npm i less --save
npm i less-loader --save
2.样式
代码如下(示例):
<template>
<div class="spec-preview">
<img :src="myImg.imgUrl" />
<div class="event" @mousemove="handler"></div>
<div class="imgTela">
<img :src="myImg.imgUrl" ref="imgTela" />
</div>
<div class="layer" ref="layer"></div>
</div>
</template>
<script>
export default {
name: 'App',
data() {
return {
img: []
}
},
methods: {
handler(e) {
// 获取元素
let layer = this.$refs.layer
let imgTela = this.$refs.imgTela
// 获取小方块到大方块的距离
let left = e.offsetX - layer.offsetWidth / 2
let top = e.offsetY - layer.offsetHeight / 2
// 添加约束
if (left <= 0) left = 0
if (left >= layer.offsetWidth) left = layer.offsetWidth
if (top <= 0) top = 0
if (top >= layer.offsetHeight) top = layer.offsetHeight
// 设置偏移量
layer.style.left = left + 'px'
layer.style.top = top + 'px'
imgTela.style.left = -2 * left + 'px'
imgTela.style.top = -2 * top + 'px'
}
},
computed: {
myImg() {
return this.img[0] || {}
}
}
}
</script>
<style lang="less">
.spec-preview {
position: relative;
width: 600px;
height: 342px;
margin: 20px auto;
img {
width: 100%;
height: 100%;
}
.event {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
z-index: 998;
}
.layer {
width: 50%;
height: 50%;
position: absolute;
left: 0;
top: 0;
display: none;
}
.imgTela {
width: 100%;
height: 100%;
position: absolute;
top: -1px;
left: 100%;
border: 1px solid #aaa;
overflow: hidden;
z-index: 998;
display: none;
background: white;
img {
width: 200%;
max-width: 200%;
height: 200%;
position: absolute;
left: 0;
top: 0;
}
}
.event:hover ~ .layer,
.event:hover ~ .imgTela {
display: block;
}
}
</style>
该处使用的url网络请求的数据,所以img默认是个空数组