实时获取页面比例
- 移动端设计稿通常为 750px
- 当前窗口的宽为
window.innerWidth
- 通过 useResizeObserver 可实时监听窗口大小的变化
src/stores/theme.ts
export const useThemeStroe = defineStore('theme', () => {
const rate = ref(0)
function setRate(newRate: number) {
rate.value = newRate
}
return { rate, setRate }
})
src/App.vue
import { useThemeStroe } from '@/stores/theme'
const themeStroe = useThemeStroe()
useResizeObserver(document.body, () => {
const w_width = window.innerWidth
// 设计稿的宽度
const contentWidth = 750
themeStroe.setRate((w_width / contentWidth).toFixed(2))
})
src/pages/index.vue
页面中获取比例
import { useThemeStroe } from '@/stores/theme'
const themeStroe = useThemeStroe()
:style="{ height: themeStroe.rate * 24 + 'rem' }"
指定尺寸内按比例缩放,超过指定尺寸保持高度不变的图片
src/pages/index.vue
页面中的图片高度根据随窗口变化动态更新 rate 计算得到
<img
class="w-full"
style="object-fit: cover"
:style="{ height: themeStroe.rate * 24 + 'rem' }"
src="https://img0.baidu.com/it/u=998088135,496941855&fm=253&fmt=auto&app=138&f=PNG?w=600&h=300"
/>
import { useThemeStroe } from '@/stores/theme'
const themeStroe = useThemeStroe()
src/App.vue
import { useThemeStroe } from '@/stores/theme'
const themeStroe = useThemeStroe()
useResizeObserver(document.body, () => {
const w_width = window.innerWidth
// 设计稿的宽度
const contentWidth = 750
themeStroe.setRate(w_width < contentWidth ? +(w_width / contentWidth).toFixed(2) : 1)
})
src/stores/theme.ts
export const useThemeStroe = defineStore('theme', () => {
const rate = ref(0)
function setRate(newRate: number) {
rate.value = newRate
}
return { rate, setRate }
})