zoom.client.ts 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. export default defineNuxtPlugin((nuxtApp) => {
  2. if (import.meta.client) {
  3. // 存储上一次的稳定宽度,避免重复计算
  4. let lastStableWidth = 0
  5. // 核心:获取稳定的窗口宽度(解决临时值问题)
  6. const getStableWidth = () => {
  7. // 读取布局宽度(比 innerWidth 更精准,不受滚动条/缩放影响)
  8. return document.documentElement.clientWidth
  9. }
  10. const setZoom = () => {
  11. const html = document.documentElement
  12. const width = getStableWidth() || window.innerWidth
  13. if (width === lastStableWidth && width !== 0) return
  14. lastStableWidth = width
  15. let zoom = 1
  16. if (width >= 768 && width < 1440) {
  17. zoom = width / 1920
  18. }
  19. html.style.zoom = zoom.toString()
  20. html.classList.add('zoom-ready')
  21. }
  22. document.documentElement.classList.remove('zoom-ready')
  23. setZoom()
  24. nuxtApp.hook('app:mounted', () => {
  25. requestAnimationFrame(setZoom)
  26. })
  27. window.addEventListener('resize', setZoom)
  28. return {
  29. provide: {
  30. refreshZoom: setZoom,
  31. },
  32. }
  33. }
  34. return {
  35. provide: {
  36. refreshZoom: () => {},
  37. },
  38. }
  39. })