Skip to content

Commit

Permalink
feat: 拖拽函数增加拖拽限定区域
Browse files Browse the repository at this point in the history
  • Loading branch information
xiaozzzi committed Apr 2, 2024
1 parent ce77d82 commit 5de8435
Showing 1 changed file with 29 additions and 16 deletions.
45 changes: 29 additions & 16 deletions blossom-editor/src/renderer/src/scripts/draggable.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,21 @@
import { onBeforeUnmount, onMounted, watchEffect } from 'vue'
import type { Ref } from 'vue'

/**
* 元素拖拽
* @param targetRef 拖拽时移动的元素
* @param dragRef 拖拽时拖动的元素
* @param regionRef 元素可以拖拽的范围
*/
export const useDraggable = (
targetRef: Ref<HTMLElement | undefined>,
dragRef: Ref<HTMLElement | undefined>,
regionRef?: Ref<HTMLElement | undefined>
// draggable: ComputedRef<boolean>
) => {
let transform = {
offsetX: 0,
offsetY: 0,
offsetY: 0
}

const onMousedown = (e: MouseEvent) => {
Expand All @@ -22,27 +29,33 @@ export const useDraggable = (
const targetWidth = targetRect.width
const targetHeight = targetRect.height

const clientWidth = document.documentElement.clientWidth
const clientHeight = document.documentElement.clientHeight
let clientWidth = document.documentElement.clientWidth
let clientHeight = document.documentElement.clientHeight
let minLeft = -targetLeft + offsetX
let minTop = -targetTop + offsetY

if (regionRef) {
console.log(regionRef.value!.getBoundingClientRect())
const rect = regionRef.value!.getBoundingClientRect()
clientWidth = rect.width + rect.x
clientHeight = rect.height + rect.y
minLeft += rect.x
minTop += rect.y
} else {
clientWidth = document.documentElement.clientWidth
clientHeight = document.documentElement.clientHeight
}

const minLeft = -targetLeft + offsetX
const minTop = -targetTop + offsetY
const maxLeft = clientWidth - targetLeft - targetWidth + offsetX
const maxTop = clientHeight - targetTop - targetHeight + offsetY

const onMousemove = (e: MouseEvent) => {
const moveX = Math.min(
Math.max(offsetX + e.clientX - downX, minLeft),
maxLeft
)
const moveY = Math.min(
Math.max(offsetY + e.clientY - downY, minTop),
maxTop
)
const moveX = Math.min(Math.max(offsetX + e.clientX - downX, minLeft), maxLeft)
const moveY = Math.min(Math.max(offsetY + e.clientY - downY, minTop), maxTop)

transform = {
offsetX: moveX,
offsetY: moveY,
offsetY: moveY
}
targetRef.value!.style.transform = `translate(${moveX}px, ${moveY}px)`
}
Expand Down Expand Up @@ -71,7 +84,7 @@ export const useDraggable = (
onMounted(() => {
watchEffect(() => {
// if (draggable.value) {
onDraggable()
onDraggable()
// } else {
// offDraggable()
// }
Expand All @@ -81,4 +94,4 @@ export const useDraggable = (
onBeforeUnmount(() => {
offDraggable()
})
}
}

0 comments on commit 5de8435

Please sign in to comment.