div左右两边50%拖拽功能

发布时间 2023-08-11 15:01:15作者: Amyad
<template>
<div id="app">
<div class="container">
<div class="left" :style="{ width: leftWidth + '%' }">
<h1>Left Content</h1>
</div>
<div class="dragbar" @mousedown="startResize"></div>
<div class="right" :style="{ width: rightWidth + '%' }">
<h1>Right Content</h1>
</div>
</div>
</div>
</template>

<script>
export default {
data() {
return {
isResizing: false,
startX: 0,
leftWidth: 50,
rightWidth: 50,
};
},
computed: {},
methods: {
startResize(e) {
this.isResizing = true;
this.startX = e.clientX;
},
resize(e) {
if (!this.isResizing) return;
const containerWidth = this.$el.offsetWidth;
const offsetX = e.clientX - this.startX;
const percentageOffsetX = (offsetX / containerWidth) * 100;
this.leftWidth += percentageOffsetX;
this.rightWidth -= percentageOffsetX;
this.startX = e.clientX;
},
stopResize() {
this.isResizing = false;
},
},
mounted() {
window.addEventListener("mousemove", this.resize);
window.addEventListener("mouseup", this.stopResize);
},
beforeDestroy() {
window.removeEventListener("mousemove", this.resize);
window.removeEventListener("mouseup", this.stopResize);
},
};
</script>

<style scoped>
.container {
display: flex;
height: 300px;
}

.left,
.right {
height: 100%;
overflow: auto;
}

.dragbar {
width: 5px;
cursor: col-resize;
background-color: #ccc;
}

.left {
background-color: #f0f0f0;
}

.right {
background-color: #ccc;
}
</style>