传统的方式

因为传统的方式都很熟悉,我就不写了,主要是改进版和最终版的写法

改进版

html&css

1
2
3
4
5
6
<style>
.box {
background-color:pink;
}
</style>
<div class="box"></div>

Js

1
2
3
4
5
6
7
8
9
10
11
12
13
//=====================S=移动端适配=================
//==designWidth是设计稿的大小
//==rem2px是等分多少份后,每份站多少像素(px)
var designWidth = 640, rem2px = 32;
//=========S=设置rem的大小============
document.documentElement.style.fontSize =
((window.innerWidth / designWidth) * rem2px) + 'px';
//=========E=设置rem的大小============
//=====================E=移动端适配=================
var box = document.querySelector('.box');
console.log( box )
box.style.width = '1rem';
box.style.height = '1rem'

最终版

html&css

1
2
3
4
5
6
<style>
.box {
background-color: pink;
}
</style>
<div class="box"></div>

Js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//=====================S=rem适配封装============================
//==主要是部分Android手机会有兼容问题,所以封装这个方法,从而在适配的同时,兼容各种移动设备
//==支持屏幕旋转
function adapt(designWidth, rem2px){
var d = window.document.createElement('div');
d.style.width = '1rem';
d.style.display = "none";
var head = window.document.getElementsByTagName('head')[0];
head.appendChild(d);
var defaultFontSize = parseFloat(window.getComputedStyle(d, null).getPropertyValue('width'));
d.remove();
document.documentElement.style.fontSize = window.innerWidth / designWidth * rem2px / defaultFontSize * 100 + '%';
var st = document.createElement('style');
var portrait = "@media screen and (min-width: "+window.innerWidth+"px) {html{font-size:"+ ((window.innerWidth/(designWidth/rem2px)/defaultFontSize)*100) +"%;}}";
var landscape = "@media screen and (min-width: "+window.innerHeight+"px) {html{font-size:"+ ((window.innerHeight/(designWidth/rem2px)/defaultFontSize)*100) +"%;}}"
st.innerHTML = portrait + landscape;
head.appendChild(st);
return defaultFontSize
};
//=====================E=rem适配封装============================
var fontSize = adapt( 640, 32 ),
box = document.querySelector('.box');
box.style.cssText = 'width:1rem;height:1rem';
console.log( fontSize );

最终结果

Aaron Swartz