Skip to content

Commit

Permalink
fix(useScrollLock): support using window or document (#3319)
Browse files Browse the repository at this point in the history
  • Loading branch information
Zhaolin Liang committed Aug 25, 2023
1 parent c1b296c commit 8acdb47
Showing 1 changed file with 18 additions and 4 deletions.
22 changes: 18 additions & 4 deletions packages/core/useScrollLock/index.ts
Expand Up @@ -43,6 +43,19 @@ function preventDefault(rawEvent: TouchEvent): boolean {
return false
}

function getTargetElement(
element: MaybeRefOrGetter<HTMLElement | SVGElement | Window | Document | null | undefined>,
): HTMLElement | SVGElement | null | undefined {
const el = toValue(element)
if (el instanceof Window)
return window.document.documentElement

if (el instanceof Document)
return document.documentElement

return el
}

/**
* Lock scrolling of the element.
*
Expand All @@ -58,8 +71,9 @@ export function useScrollLock(
let initialOverflow: CSSStyleDeclaration['overflow']

watch(toRef(element), (el) => {
if (el) {
const ele = el as HTMLElement
const target = getTargetElement(el)
if (target) {
const ele = target as HTMLElement
initialOverflow = ele.style.overflow
if (isLocked.value)
ele.style.overflow = 'hidden'
Expand All @@ -69,7 +83,7 @@ export function useScrollLock(
})

const lock = () => {
const ele = (toValue(element) as HTMLElement)
const ele = getTargetElement(element)
if (!ele || isLocked.value)
return
if (isIOS) {
Expand All @@ -85,7 +99,7 @@ export function useScrollLock(
}

const unlock = () => {
const ele = (toValue(element) as HTMLElement)
const ele = getTargetElement(element)
if (!ele || !isLocked.value)
return
isIOS && stopTouchMoveListener?.()
Expand Down

0 comments on commit 8acdb47

Please sign in to comment.