fix(Popup): lockScroll not work #7738

This commit is contained in:
chenjiahan
2020-12-27 21:13:07 +08:00
parent 82acfb2f6e
commit c114a0ef47
6 changed files with 78 additions and 18 deletions

View File

@@ -1,22 +1,70 @@
let count = 0;
import { Ref } from 'vue';
import { getScrollParent, supportsPassive } from '@vant/use';
import { useTouch } from './use-touch';
import { preventDefault } from '../utils';
const CLASSNAME = 'van-overflow-hidden';
let totalLockCount = 0;
const BODY_LOCK_CLASS = 'van-overflow-hidden';
export function useLockScroll(
rootRef: Ref<HTMLElement | undefined>,
shouldLock: () => boolean
) {
const touch = useTouch();
const onTouchMove = (event: TouchEvent) => {
touch.move(event);
const direction = touch.deltaY.value > 0 ? '10' : '01';
const el = getScrollParent(
event.target as Element,
rootRef.value
) as HTMLElement;
const { scrollHeight, offsetHeight, scrollTop } = el;
let status = '11';
if (scrollTop === 0) {
status = offsetHeight >= scrollHeight ? '00' : '01';
} else if (scrollTop + offsetHeight >= scrollHeight) {
status = '10';
}
if (
status !== '11' &&
touch.isVertical() &&
!(parseInt(status, 2) & parseInt(direction, 2))
) {
preventDefault(event, true);
}
};
export function useLockScroll(shouldLock: () => boolean) {
const lock = () => {
if (shouldLock()) {
if (!count) {
document.body.classList.add(CLASSNAME);
document.addEventListener('touchstart', touch.start);
document.addEventListener(
'touchmove',
onTouchMove,
supportsPassive ? { passive: false } : false
);
if (!totalLockCount) {
document.body.classList.add(BODY_LOCK_CLASS);
}
count++;
totalLockCount++;
}
};
const unlock = () => {
if (shouldLock() && count) {
count--;
if (!count) {
document.body.classList.remove(CLASSNAME);
if (shouldLock() && totalLockCount) {
document.removeEventListener('touchstart', touch.start);
document.removeEventListener('touchmove', onTouchMove);
totalLockCount--;
if (!totalLockCount) {
document.body.classList.remove(BODY_LOCK_CLASS);
}
}
};