var rem = {
baseRem: 40,
// 基準(zhǔn)字號怠缸,按照iphone6應(yīng)該為20护奈,此處擴大2倍硼控,便于計算
baseWidth: 750,
// 基準(zhǔn)尺寸寬悬而,此處是按照ihpone6的尺寸
rootEle: document.getElementsByTagName("html")[0],
initHandle: function() {
this.setRemHandle();
this.resizeHandle();
},
setRemHandle: function() {
var clientWidth = document.documentElement.clientWidth || document.body.clientWidth;
this.rootEle.style.fontSize = clientWidth * this.baseRem / this.baseWidth + "px";
},
resizeHandle: function() {
var that = this;
window.addEventListener("resize",
function() {
setTimeout(function() {
that.setRemHandle();
},
300);
});
}
};
rem.initHandle();
三:多屏適配布局問題
使用相對單位:rem
原理:針對不同手機屏幕尺寸和dpr動態(tài)的改變根節(jié)點html的font-size大小(基準(zhǔn)值)峦朗。
任意瀏覽器的默認(rèn)字體高都是16px份乒。所有未經(jīng)調(diào)整的瀏覽器都符合: 1rem=16px。那么12px=0.75rem,10px=0.625rem椰憋。為了簡化font-size的換算,需要在css中的html選擇器中聲明font-size=62.5%赔退,這就使rem值變?yōu)?16px62.5%=10px, 這樣12px=1.2rem, 10px=1rem, 也就是說只需要將原來的px數(shù)值除以10橙依,然后換上rem作為單位就行了。*
當(dāng)我們在根節(jié)點<html>上設(shè)置了font-size基準(zhǔn)值以后硕旗,在文檔中有使用rem單位的屬性值都是相對于根節(jié)點font-size的一個相對值窗骑。比如說一些元素的屬性如width,height,margin等。也正是這個原因漆枚,現(xiàn)在很多網(wǎng)站的移動端網(wǎng)站都在使用rem單位作為適配工具创译。
注意事項:
1.整體的布局還是使用百分比
2.使用rem的最佳場景是,遇到例如多列帶有圖片的列表,常常需要圖片固定寬高比
3.研究了一些網(wǎng)站,比如淘寶墙基,對字體字體一般情況建議使用px
4.出現(xiàn)1px像素線的地方软族,仍舊使用border-width:1px;而不是border-width:.1rem
/**
* [以iPhone6的設(shè)計稿為例js動態(tài)設(shè)置文檔 rem 值]
* @param {[type]} currClientWidth [當(dāng)前客戶端的寬度]
* @param {[type]} fontValue [計算后的 fontvalue值]
* @return {[type]} [description]
*/
<script>
var currClientWidth, fontValue,originWidth;
//originWidth用來設(shè)置設(shè)計稿原型的屏幕寬度(這里是以Iphone 6為原型的設(shè)計稿)
originWidth=375;
__resize();
//注冊 resize事件
window.addEventListener('resize', __resize, false);
function __resize() {
currClientWidth = document.documentElement.clientWidth;
//這里是設(shè)置屏幕的最大和最小值時候給一個默認(rèn)值
if (currClientWidth > 640) currClientWidth = 640;
if (currClientWidth < 320) currClientWidth = 320;
//
fontValue = ((62.5 * currClientWidth) /originWidth).toFixed(2);
document.documentElement.style.fontSize = fontValue + '%';
}
</script>