div拖拽改变宽高

在这里插入图片描述

目前是点击按照右下角边框拖拽改变大小
如果要点击按住内容拖拽也改变大小
则传入事件 $ 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>

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值