思路:通过flex布局进行分配空间,然后通过这些空间来控制图片的空间(父组件使用overflow:hidden)实现覆盖,然后通过添加事件使分割线跟随鼠标移动即可。
<template>
<div class="imgC" ref="container2" @mousemove="handleMouseMove">
<div class="img1" :style="{ width: img1Width + 'px' }">
<img src="img1.src" class="imgW" />
</div>
<div class="line" ref="line" ></div>
<div class="img2">
<img src="img2.src" class="imgW" />
</div>
</div>
</template>
<style scoped>
.imgC {
display: flex;
width: 500px;
height: 300px;
overflow: hidden;
cursor:e-resize;
}
.img1 {
overflow: hidden;
}
.img2 {
flex: 1;
overflow: hidden;
transform: scaleX(-1); /* 水平翻转,实现镜像效果 */
}
.imgW {
width: 500px;
}
.line {
height: 100%;
width: 2px;
background-color: black;
position: relative;
}
</style>
<script>
export default {
data() {
return {
img1Width: 500, // 初始化 img1 的宽度
}
methods: {
handleMouseMove(event) {
const container = this.$refs.container2;
const line = this.$refs.line;
const mouseX = event.clientX - container.getBoundingClientRect().left;
this.img1Width = mouseX;
line.style.left = mouseX + 'px';
},
}
};
</script>