- 1. 百分比适配
- 2. viewport 适配
- 3. rem 适配
- 4. 彈性盒模型
- box
- flex
- 補充
- 擷取裝置寬度
1. 百分比适配
-
缺陷
高度百分比不太好計算,不建議單獨使用,配合其他方案使用
<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>
<div class="box4"></div>
div {
width: %;
height: px;
float: left
}
.box1 { background: red }
.box2 { background: blue }
.box3 { background: green }
.box4 { background: yellow }
2. viewport 适配
通過JS計算比例,動态生成
meta viewport
标簽
-
初始比例initial-scale
-
最小縮放比例minimum-scale
-
最大縮放比例maximum-scale
(function(){
// 擷取目前螢幕寬度
var w = window.screen.width;
// 目标尺寸寬度,設計圖寬度以 640px 為例
var targetW = ;
// 縮放比例:目前尺寸/目标尺寸
var scale = w/targetW;
// 建立 meta 标簽,動态設定視口
var meta = document.createElement("meta");
meta.name = "viewport";
meta.content = "user-scalable=no,initial-scale=" + scale + ",minimum-scale=" + scale + ",maximum-scale=" + scale;
// 插入 head 中
document.head.appendChild(meta);
})()
3. rem 适配
- 設計圖選取,以
設計寬度為例640px
- 使用
機關,根據根節點rem
的字型大小進行計算html
// 擷取 document 元素
var html = document.documentElement;
// 擷取裝置寬度
var deviceWidth = html.getBoundingClientRect().width;
// 設定根元素 html 字型大小,這裡按 640/100 的比例計算
html.style.fontSize = deviceWidth/ + 'px';
- 現在,css實際尺寸與圖紙尺寸比例為
,1:100
1rem = 100px
div {
// 設計圖尺寸為100px,則css設定為 1rem
width: rem;
}
4. 彈性盒模型
box
flex
補充
擷取裝置寬度
// 擷取 html 根元素節點
var html = document.documentElement;
// 擷取裝置寬度
var deviceWidth1 = html.clientWidth;
var deviceWidth2 = html.getBoundingClientRect().width
// 兩種方式擷取的結果一樣
console.log(deviceWidth1 === deviceWidth2) // => true
-
和clientWidth
的差別getBoundingClientRect().width