rem_0">关于rem适配
- 适配对于我,比较头痛,发现自己在项目中用的那套方式,不方便计算且有点不精准。(也许没有正确使用), 大神朋友推荐了其它方式, 一起来测试吧。。。
测试了以下方式
方式一: 使用 JS 计算两种(方便)
A
<script>
//window.onload = function () { //加onload,会出现加载页面集体缩放问题
window.onresize = function () {
getRem(750, 100)
}
function getRem(pwidth, prem) {
var html = document.getElementsByTagName("html")[0];
var oWidth = document.body.clientWidth || document.documentElement.clientWidth;
console.log(oWidth)
html.style.fontSize = oWidth / pwidth * prem + "px";
console.log(html.style.fontSize = oWidth / pwidth * prem + "px")
}
/*720代表设计师给的设计稿的宽度,你的设计稿是多少,就写多少;100代表换算比例,这里写100是
为了以后好算,比如,你测量的一个宽度是100px,就可以写为1rem,以及1px=0.01rem等等*/
getRem(750, 100)
//}
</script>
B
(function(d, w) {
const doc = d.documentElement;
function rem() {
const width = Math.min(doc.getBoundingClientRect().width, 768);
doc.style.fontSize = width / 7.5 + 'px';
}
rem();
w.addEventListener('resize', rem);
})(document, window);
flexiblejs_51">方式二: 使用 flexible.js
@r: 75rem;
// 测量值 / 设置rem变量
.wrap {
height: 100 / @r;
}
Demo图
方式三: 设置根字号 + 媒体查询
* 首先 设置 html 根据号 (自定义)
* 定义媒体查询: 根据不同尺寸计算字号
初始化
// 1. 这里以 12px 作为根字号
// 2. 360宽度的 13.5是如何计算的呢?
【360当前屏 / 320最小屏 * 12根字号】 以此类推
html {
font-size: 12px;
}
@media only screen and (min-width: 320px) {
html{
font-size: 12px;
}
}
@media only screen and (min-width: 360px) {
html {
font-size: 13.5px !important;
}
}
@media only screen and (min-width: 375px) {
html {
font-size: 14.0625px !important;
}
}
@media only screen and (min-width: 400px) {
html {
font-size: 15px !important;
}
}
@media only screen and (min-width: 412px) {
html {
font-size: 15.45px !important;
}
}
@media only screen and (min-width: 414px) {
html {
font-size: 15.525px !important;
}
}
@media only screen and (min-width: 640px) {
html {
font-size: 24px !important;
}
}
使用
1. ps: 某元素测量 高度为90px
2. 计算: 90 / 2(设计稿2倍图) / 12根字号
// 除 2 要根据设计稿,
【我这次项目中 750设计稿,计算不太准, 也许跟 除2倍图有关系】
| ps: 个人比较喜欢 第一种方式, 感谢朋友指导, 望请各位大神指教更好的方式。。。