在vue中盒子大小由两个控件来拖拽调整的代码,其中一个控件负责宽度,另一个负责高度

<template>
  <div class="box" :style="{width: width + 'px', height: height + 'px'}">
    <!-- 宽度控件 -->
    <div class="width-control" :style="{left: width - 10 + 'px'}" @mousedown.prevent="startDragWidth"></div>
    <!-- 高度控件 -->
    <div class="height-control" :style="{top: height - 10 + 'px'}" @mousedown.prevent="startDragHeight"></div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 盒子宽度和高度
      width: 200,
      height: 200,
      // 拖拽相关参数
      isDraggingWidth: false,
      isDraggingHeight: false,
      startX: 0,
      startY: 0
    }
  },
  methods: {
    startDragWidth(e) {
      this.isDraggingWidth = true;
      this.startX = e.clientX;
    },
    startDragHeight(e) {
      this.isDraggingHeight = true;
      this.startY = e.clientY;
    },
    endDrag() {
      this.isDraggingWidth = false;
      this.isDraggingHeight = false;
    },
    handleMouseMove(e) {
      if (this.isDraggingWidth) {
        const dx = e.clientX - this.startX;
        this.width += dx;
        this.startX = e.clientX;
      } else if (this.isDraggingHeight) {
        const dy = e.clientY - this.startY;
        this.height += dy;
        this.startY = e.clientY;
      }
    }
  },
  mounted() {
    document.addEventListener('mousemove', this.handleMouseMove);
    document.addEventListener('mouseup', this.endDrag);
  },
  beforeDestroy() {
    document.removeEventListener('mousemove', this.handleMouseMove);
    document.removeEventListener('mouseup', this.endDrag);
  }
}
</script>

<style scoped>
.box {
  position: relative;
  border: 1px solid #ccc;
}
.width-control, .height-control {
  position: absolute;
  width: 10px;
  height: 10px;
  background-color: #f00;
  cursor: pointer;
}
.width-control {
  top: 50%;
  transform: translate(-50%, -50%);
}
.height-control {
  left: 50%;
  transform: translate(-50%, -50%);
}
</style>

这个组件中,我使用了两个 div 元素作为宽度和高度控件,并用样式将它们定位到了盒子的右边和底部。当鼠标按下时,我们通过 @mousedown.prevent="startDragWidth"@mousedown.prevent="startDragHeight" 监听鼠标事件,并设置相应的拖拽状态。在拖拽过程中,我们监听 documentmousemove 事件,并根据鼠标移动的距离调整盒子的宽度或高度。最后,在鼠标松开时,我们重置拖拽状态。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值