<script lang="ts" setup>
import {ref, reactive, onMounted} from 'vue'
let startclientX = ref(0) // 元素拖拽前距离浏览器的X轴位置
let startclientY = ref(0) //元素拖拽前距离浏览器的Y轴位置
let elLeft = ref(770) // 元素的左偏移量
let elTop = ref(220) // 元素的右偏移量
let elWidth = ref(200)
let elHeight = ref(100)
// 拖拽开始事件
function dragstart(e) {
startclientX.value = e.clientX; // 记录拖拽元素初始位置
startclientY.value = e.clientY;
}
// 拖拽完成事件
function dragend(e) {
let x = e.clientX - startclientX.value; // 计算偏移量
let y = e.clientY - startclientY.value;
elLeft.value += x; // 实现拖拽元素随偏移量移动
elTop.value += y;
//记录拖放后的位置
console.log(elLeft.value+", "+elTop.value+", " +elWidth.value+", "+elHeight.value)
}
</script>
<template>
<div
class="drag_box"
draggable="true"
@dragstart="dragstart($event)"
@dragend="dragend($event)"
:style="`left:${elLeft}px;top:${elTop}px;width:${elWidth}px;height:${elHeight}px;`"
>
拖放案例
</div>
</template>
<style scoped>
.drag_box {
background: skyblue;
position: absolute;
z-index: 10;
}
</style>