rem是根據html的font-size大小來變化,正是基於這個出發,咱們能夠在每個設備下根據設備的寬度設置對應的html字號,從而實現了自適應佈局。更多介紹請看這篇文章:rem是如何實現自適應佈局的。javascript
目前有兩種,一種是根據js來調整html的字號,另外一種則是經過媒體查詢來調整字號。css
;(function(designWidth, maxWidth) { var doc = document, win = window; var docEl = doc.documentElement; var tid; var rootItem,rootStyle; function refreshRem() { var width = docEl.getBoundingClientRect().width; if (!maxWidth) { maxWidth = 540; }; if (width > maxWidth) { width = maxWidth; } //與淘寶作法不一樣,直接採用簡單的rem換算方法1rem=100px var rem = width * 100 / designWidth; //兼容UC開始 rootStyle="html{font-size:"+rem+'px !important}'; rootItem = document.getElementById('rootsize') || document.createElement("style"); if(!document.getElementById('rootsize')){ document.getElementsByTagName("head")[0].appendChild(rootItem); rootItem.id='rootsize'; } if(rootItem.styleSheet){ rootItem.styleSheet.disabled||(rootItem.styleSheet.cssText=rootStyle) }else{ try{rootItem.innerHTML=rootStyle}catch(f){rootItem.innerText=rootStyle} } //兼容UC結束 docEl.style.fontSize = rem + "px"; }; refreshRem(); win.addEventListener("resize", function() { clearTimeout(tid); //防止執行兩次 tid = setTimeout(refreshRem, 300); }, false); win.addEventListener("pageshow", function(e) { if (e.persisted) { // 瀏覽器後退的時候從新計算 clearTimeout(tid); tid = setTimeout(refreshRem, 300); } }, false); if (doc.readyState === "complete") { doc.body.style.fontSize = "16px"; } else { doc.addEventListener("DOMContentLoaded", function(e) { doc.body.style.fontSize = "16px"; }, false); } })(640, 640);
你能夠把上面的代碼內嵌到html的head中,換算比例是1rem=100px,爲了計算方便,你能夠在個人一個github項目下載完整的結構和一個壓縮的js。html
項目主頁前端
上面代碼中的關鍵代碼是:java
var width = docEl.getBoundingClientRect().width; var rem = width * 100 / designWidth; docEl.style.fontSize = rem + "px";
說到底,上面的js代碼不就是根據不一樣的設備調整對應的html字號嘛,那麼咱們根據實際的設備,來加上相應的字號不就好了嗎?git
咱們知道html的默認字號是16px,則對應的設備下能夠經過設置對應的font-size使其有一致的縮放比例。github
html { font-size: 62.5% } @media only screen and (min-width: 481px) { html { font-size:94%!important } } @media only screen and (min-width: 561px) { html { font-size:109%!important } } @media only screen and (min-width: 641px) { html { font-size:125%!important } body { max-width: 640px } }
上面的代碼則是經過1rem=20px來換算的,從哪裏看出來呢?從最大的一個值640出發,假如你的設計稿是750的話,那你還要設計更多的媒體 查詢,換算比例保持一致就能夠了。那若是我想要換算比例爲1rem=100呢?按照上面的規則,最大的值爲:html:font- size:100/16*100%,其它的則按比例,好比480px,則爲480/640*(100/16*100%)。web
國內的不少人都提倡使用字體圖標或者用SVG的方式來實現,但這些在小項目中明顯是有點不實際。我一般使用下面兩種方式。瀏覽器
本文後面將繼續更新關於rem實現自適應的相關問題,若是你有問題,還請留言給我。sass