Search K
Appearance
Appearance
<template>
<div :style="[posStyleCom]" @mousedown="handleMouseDownOnShape">
<slot></slot>
</div>
</template>
<script setup>
import { reactive, computed,inject } from "vue"
const posStyle: any = reactive({
top: 0,
left: 0
})
// 当前拖拽Dom的style
const posStyleCom = computed(() => {
return {
top: `${posStyle.top}px`,
left: `${posStyle.left}px`
}
})
/**
* 鼠标按下事件,实现Dom拖拽的核心代码
* 具体实现思路:
* @param e
*/
function handleMouseDownOnShape(e: any) {
e.stopPropagation()
e.preventDefault()
// 获取当前Dom鼠标按下时候的位置 x,y
const startY = e.clientY
const startX = e.clientX
// 当前Dom的初始化位置 x,y 每次拖拽都会改变
const startTop = Number(posStyle.top)
const startLeft = Number(posStyle.left)
// Dom拖拽时触发,核心方法
const move = (moveEvent: any) => {
// 获取当前Dom移动到的目标地点位置 x,y
const curX = moveEvent.clientX
const curY = moveEvent.clientY
// 计算出现在Dom拖拽后应该在的位置
// 拖拽后的位置 = 当前拖拽到的位置 - 鼠标按下时候的位置 + 当前Dom原始的值
const tempTop = curY - startY + startTop
const tempLeft = curX - startX + startLeft
posStyle.top = tempTop
posStyle.left = tempLeft
}
// 鼠标放开事件
const up = () => {
e.stopPropagation()
e.preventDefault()
document.removeEventListener('mousemove', move)
document.removeEventListener('mouseup', up)
}
document.addEventListener('mousemove', move)
document.addEventListener('mouseup', up)
}
</script?