Vue3 实现拖拽动态设置div宽高

 

<template>
  <div class="container" ref="container">
    <div class="drag" @mousedown="onTdMousedown($event)"></div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';

// 目标元素
const props = defineProps<{
  target: HTMLElement;
}>();

const domInfo = reactive({
  baseW: 0,
  baseH: 0
});

const container = ref<HTMLElement>(null);

const updateTarget = (event: MouseEvent) => {
  if (!container.value) {
    console.error('drag--- 请传入一个HTMLElement节点');
    return;
  }
  // movementX/movementY
  // 两个鼠标移动事件间隔时间中当中鼠标移动的相对坐标;
  domInfo.baseW = container.value.clientWidth;
  domInfo.baseH = container.value.clientHeight;
  container.value!.style.width = `${domInfo.baseW + event.movementX}px`;
  container.value!.style.height = `${domInfo.baseH + event.movementY}px`;
};
// change 回调方式
const onTdMousedown = (e: MouseEvent) => {
  window.addEventListener('mousemove', updateTarget);
  window.onmouseup = function () {
    window.onmouseup = null;
    window.removeEventListener('mousemove', updateTarget);
  };
};
</script>

<style lang="scss" scoped>
.drag {
  position: absolute;
  width: 16px;
  height: 16px;
  bottom: 10px;
  // background: red;
  right: 10px;
  z-index: 999;
  border-radius: inherit;
  box-shadow: 2px 2px 0px -1px blue;
  cursor: move;
}

.container {
  width: 100px;
  height: 100px;
  background-color: #ccc;
  position: relative;
}
</style>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

清云随笔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值