Skip to content

Commit

Permalink
fix(useDraggable): element can't relative parent element move (#3531)
Browse files Browse the repository at this point in the history
Co-authored-by: banruo <shl@dataqin.com>
  • Loading branch information
huiliangShen and banruo committed Nov 9, 2023
1 parent c703bbe commit 082462d
Showing 1 changed file with 17 additions and 6 deletions.
23 changes: 17 additions & 6 deletions packages/core/useDraggable/index.ts
Expand Up @@ -142,11 +142,13 @@ export function useDraggable(
return
if (toValue(exact) && e.target !== toValue(target))
return
const container = toValue(containerElement) ?? toValue(target)
const rect = container!.getBoundingClientRect()

const container = toValue(containerElement)
const containerRect = container?.getBoundingClientRect?.()
const targetRect = toValue(target)!.getBoundingClientRect()
const pos = {
x: e.clientX - rect.left,
y: e.clientY - rect.top,
x: e.clientX - (container ? targetRect.left - containerRect!.left : targetRect.left),
y: e.clientY - (container ? targetRect.top - containerRect!.top : targetRect.top),
}
if (onStart?.(pos, e) === false)
return
Expand All @@ -159,11 +161,20 @@ export function useDraggable(
if (!pressedDelta.value)
return

const container = toValue(containerElement)
const containerRect = container?.getBoundingClientRect?.()
const targetRect = toValue(target)!.getBoundingClientRect()
let { x, y } = position.value
if (axis === 'x' || axis === 'both')
if (axis === 'x' || axis === 'both') {
x = e.clientX - pressedDelta.value.x
if (axis === 'y' || axis === 'both')
if (container)
x = Math.min(Math.max(0, x), containerRect!.width - targetRect!.width)
}
if (axis === 'y' || axis === 'both') {
y = e.clientY - pressedDelta.value.y
if (container)
y = Math.min(Math.max(0, y), containerRect!.height - targetRect!.height)
}
position.value = {
x,
y,
Expand Down

0 comments on commit 082462d

Please sign in to comment.