Vue3 实现拖拽动态设置div宽高
【代码】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>
更多推荐
已为社区贡献17条内容
所有评论(0)