vue3大屏适配实现方案:rem
摘要:页面所用单位全部改为rem 复制该代码到文件中 修改代码中的设计稿尺寸 在组件中引入该Hook,并使用 import { useScreenAdaptation } from '@/hooks/useScreen'; useScreenAdaptation( // hooks/useScreen.js import { ref, onMounted, onUnmounted } from 'vue'; export function useScreenAdaptation( { // 设计稿尺寸 const designWidth = 1680; const designHeight = 1050; // 当前缩放比例 const scale = ref(1 ; // 计算并设置根字体大小 const calculateRootFontSize = ( =<!--autointro-->...
- 页面所用单位全部改为rem
- 复制该代码到文件中
修改代码中的设计稿尺寸
- 在组件中引入该Hook,并使用
import { useScreenAdaptation } from ‘@/hooks/useScreen’;
useScreenAdaptation()
// hooks/useScreen.js
import { ref, onMounted, onUnmounted } from 'vue';
export function useScreenAdaptation() {
// 设计稿尺寸
const designWidth = 1680;
const designHeight = 1050;
// 当前缩放比例
const scale = ref(1);
// 计算并设置根字体大小
const calculateRootFontSize = () => {
const clientWidth = window.innerWidth || document.documentElement.clientWidth;
const clientHeight = window.innerHeight || document.documentElement.clientHeight;
// 计算宽度和高度的缩放比例
const scaleWidth = clientWidth / designWidth;
const scaleHeight = clientHeight / designHeight;
// 取较小的缩放比例,确保内容完全显示
scale.value = Math.min(scaleWidth, scaleHeight);
// 设置根元素字体大小
document.documentElement.style.fontSize = `${16 * scale.value}px`;
return scale.value;
};
// 监听窗口大小变化
const handleResize = () => {
requestAnimationFrame(() => calculateRootFontSize())
};
// 初始化
onMounted(() => {
calculateRootFontSize();
window.addEventListener('resize', handleResize);
});
// 清理
onUnmounted(() => {
window.removeEventListener('resize', handleResize);
});
return {
scale,
calculateRootFontSize
};
}
本文链接:https://blog.smallhao.fun/?id=35 转载需授权!
Chen’Blog版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!