- 页面所用单位全部改为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 转载需授权!
暂无评论
发表评论