目前是点击按照右下角边框拖拽改变大小
如果要点击按住内容拖拽也改变大小
则传入事件 $ event即可startDrag(index,$event)
和drag(index,$event)
以下代码可直接使用
<template>
<div>
<div>目前是点击按照右下角边框拖拽改变大小 <br> 如果要点击按住内容拖拽也改变大小 <br>则传入事件$event即可 startDrag(index,$event)和drag(index,$event)</div>
<div class="resizable-div" v-for="(item, index) in items" :key="index" ref="resizableDiv"
@mousedown="startDrag(index)" @mousemove="drag(index)" @mouseup="stopDrag">
<!-- 内容 -->
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [1, 2, 3, 4, 5, 6],
startX: 0,
startY: 0,
startWidth: 0,
startHeight: 0,
dragging: false,
activeIndex: -1
};
},
methods: {
startDrag(index, event) {
console.log(index, event);
this.activeIndex = index;
this.startX = event?.clientX;
this.startY = event?.clientY;
this.startWidth = this.$refs.resizableDiv[index].clientWidth;
this.startHeight = this.$refs.resizableDiv[index].clientHeight;
this.dragging = true;
},
drag(index, event) {
console.log(index, event);
if (this.dragging && this.activeIndex === index) {
const deltaX = event?.clientX - this.startX;
const deltaY = event?.clientY - this.startY;
this.$refs.resizableDiv[index].style.width = this.startWidth + deltaX + 'px';
this.$refs.resizableDiv[index].style.height = this.startHeight + deltaY + 'px';
}
},
stopDrag() {
this.dragging = false;
this.activeIndex = -1;
}
}
};
</script>
<style>
.resizable-div {
background-color: #1fff;
width: 100px;
height: 200px;
border: 1px solid #ddd;
resize: both;
/* 允许水平和垂直调整大小 */
overflow: auto;
/* 确保内容超出边界时出现滚动条 */
margin-bottom: 10px;
/* 添加一些间距 */
}
</style>