Blame view

Yi.Vben5.Vue3/packages/@core/composables/src/use-scroll-lock.ts 1.42 KB
515fceeb   “wangming”   框架初始化
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
  import { getScrollbarWidth, needsScrollbar } from '@vben-core/shared/utils';
  
  import {
    useScrollLock as _useScrollLock,
    tryOnBeforeUnmount,
    tryOnMounted,
  } from '@vueuse/core';
  
  export const SCROLL_FIXED_CLASS = `_scroll__fixed_`;
  
  export function useScrollLock() {
    const isLocked = _useScrollLock(document.body);
    const scrollbarWidth = getScrollbarWidth();
  
    tryOnMounted(() => {
      if (!needsScrollbar()) {
        return;
      }
      document.body.style.paddingRight = `${scrollbarWidth}px`;
  
      const layoutFixedNodes = document.querySelectorAll<HTMLElement>(
        `.${SCROLL_FIXED_CLASS}`,
      );
      const nodes = [...layoutFixedNodes];
      if (nodes.length > 0) {
        nodes.forEach((node) => {
          node.dataset.transition = node.style.transition;
          node.style.transition = 'none';
          node.style.paddingRight = `${scrollbarWidth}px`;
        });
      }
      isLocked.value = true;
    });
  
    tryOnBeforeUnmount(() => {
      if (!needsScrollbar()) {
        return;
      }
      isLocked.value = false;
      const layoutFixedNodes = document.querySelectorAll<HTMLElement>(
        `.${SCROLL_FIXED_CLASS}`,
      );
      const nodes = [...layoutFixedNodes];
      if (nodes.length > 0) {
        nodes.forEach((node) => {
          node.style.paddingRight = '';
          requestAnimationFrame(() => {
            node.style.transition = node.dataset.transition || '';
          });
        });
      }
      document.body.style.paddingRight = '';
    });
  }