html配置rem实现页面自适应
1.在js文件使用,建议放到全局js中
// 全局js文件
$(function () {// 设置根目录字体大小var baseSize = 16; // 设计稿的基准字体大小,通常是16pxvar baseWidth = 750; // 设计稿的基准宽度,通常是750pxfunction adjustFontSize() {const width =window.innerWidth ||document.documentElement.clientWidth ||document.body.clientWidth;console.log("当前页面宽度:", width);// 你可以在这里根据不同的宽度执行逻辑// if (width <= 1250) {// console.log("移动端");// baseWidth = 750;// } else {// console.log("平板");// baseWidth = 1400;// }var scale = document.documentElement.clientWidth / baseWidth; // 设计稿宽度除以基准宽度比例document.documentElement.style.fontSize =baseSize * Math.min(scale, 2) + "px"; // 最大放大到2倍}adjustFontSize(); // 页面加载时调整字体大小window.addEventListener("resize", adjustFontSize); // 监听窗口大小变化
});
2.下载单位转换插件
3.在写样式的时候使用rem单位
记得下载px转rem的插件
.ul {gap: 0.625rem /* 10/16 */;margin-top: 1.25rem /* 20/16 */;.li {flex: 1;height: 6.25rem /* 100/16 */;line-height: 6.25rem /* 100/16 */;background-color: pink;text-align: center;font-size: 16px;}
}
.text {width: 80%;margin: 1.25rem /* 20/16 */ auto;font-size: 16px;
}
如果单位使用px就不会改变大小