lock-screen.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import { onUnmounted } from 'vue'
  2. import { isClient } from '@vueuse/core'
  3. import {
  4. addClass,
  5. getScrollBarWidth,
  6. getStyle,
  7. hasClass,
  8. removeClass,
  9. } from '@element-plus/utils'
  10. export const useLockScreen = () => {
  11. let scrollBarWidth = 0
  12. let withoutHiddenClass = false
  13. let bodyPaddingRight = '0'
  14. let computedBodyPaddingRight = 0
  15. onUnmounted(() => {
  16. cleanup()
  17. })
  18. const cleanup = () => {
  19. if (!isClient) return
  20. removeClass(document.body, 'el-popup-parent--hidden')
  21. if (withoutHiddenClass) {
  22. document.body.style.paddingRight = bodyPaddingRight
  23. }
  24. }
  25. const lock = () => {
  26. if (!isClient) return
  27. withoutHiddenClass = !hasClass(document.body, 'el-popup-parent--hidden')
  28. if (withoutHiddenClass) {
  29. bodyPaddingRight = document.body.style.paddingRight
  30. computedBodyPaddingRight = Number.parseInt(
  31. getStyle(document.body, 'paddingRight'),
  32. 10
  33. )
  34. }
  35. scrollBarWidth = getScrollBarWidth()
  36. const bodyHasOverflow =
  37. document.documentElement.clientHeight < document.body.scrollHeight
  38. const bodyOverflowY = getStyle(document.body, 'overflowY')
  39. if (
  40. scrollBarWidth > 0 &&
  41. (bodyHasOverflow || bodyOverflowY === 'scroll') &&
  42. withoutHiddenClass
  43. ) {
  44. document.body.style.paddingRight = `${
  45. computedBodyPaddingRight + scrollBarWidth
  46. }px`
  47. }
  48. addClass(document.body, 'el-popup-parent--hidden')
  49. }
  50. return {
  51. lock,
  52. cleanup,
  53. }
  54. }