本文实例为大家分享了Vue2实现放大镜效果的具体代码,供大家参考,具体内容如下
一,需求描述
在使用vue进行项目开发时,需要通过鼠标在一定范围内滑动使项目图片放大以便于查看
步骤思路
- 对原图的显示空间(left) 可以将显示原图的 img 换成 canvas,来对图片进行保护
- 跟随鼠标移动时显示放大的指示区(鼠标层罩top)
- 显示层罩区域选中放大的显示空间(right)
代码部分
css部分
<style>
* {
margin: 0;
padding: 0;
}
.box {
width: 500px;
height: 300px;
position: relative;
}
.box img {
width: 100%;
height: 100%;
}
.box .cover {
width: 100px;
height: 100px;
border-radius: 50%;
background-color: rgba(0, 0, 0, .3);
position: absolute;
top: 0;
}
.covers {
width: 100%;
height: 100%;
position: absolute;
top: 0;
}
.box1 {
width: 500px;
height: 300px;
position: absolute;
top: 50px;
left: 600px;
overflow: hidden;
}
.box1 img{
width: 300%;
height: 300%;
position: absolute;
z-index: 9999;
}
</style>
html部分
<div id="root">
<div class="box">
<img src="./2.jpg" alt="">
<div @mousemove="mood" class="covers"></div>
<div class="cover" :style="tran"></div>
</div>
<div class="box1">
<img src="./2.jpg" ref="big">
</div>
</div>
vue部分
<script>
Vue.config.productionTip = false;
new Vue({
el: "#root",
data: {
tran: { top: "", left: "" }
},
methods: {
mood(e) {
let big = this.$refs.big;
let leftX = e.offsetX;
let topY = e.offsetY
if (topY <= 50) {
topY = 50
} else if (topY > 250) {
topY = 250
}
if (leftX <= 50) {
leftX = 50
} else if (leftX > 450) {
leftX = 450
}
this.tran.top = topY - 50 + 'px';
this.tran.left = leftX - 50 + 'px';
big.style.left= -2* leftX + 'px';
big.style.top= -2* topY + 'px';
}
},
})
</script>