lock-screen.ts 1.5 KB

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