rem兼容js

原文鏈接:http://caibaojian.com/simple-flexible.html

//code from http://caibaojian.com/simple-flexible.html<style id="rootFontSize">html{font-size: 100px !important;}</style>

·


來源:前端開發博客


<script type="text/javascript">

// remjs

//designWidth:設計稿的實際寬度值,需要根據實際設置

//maxWidth:製作稿的最大寬度值,需要根據實際設置

//這段js的最後面有兩個參數記得要設置,一個爲設計稿實際寬度,一個爲製作稿最大寬度,例如設計稿爲750,最大寬度爲750,則爲(750,750)

;(function(designWidth, maxWidth) {

var doc = document,

win = window,

docEl = doc.documentElement,

remStyle = document.createElement("style"),

tid;


function refreshRem() {

var width = docEl.getBoundingClientRect().width;

maxWidth = maxWidth || 540;

width>maxWidth && (width=maxWidth);

var rem = width * 100 / designWidth;

remStyle.innerHTML = 'html{font-size:' + rem + 'px;}';

}


if (docEl.firstElementChild) {

docEl.firstElementChild.appendChild(remStyle);

} else {

var wrap = doc.createElement("div");

wrap.appendChild(remStyle);

doc.write(wrap.innerHTML);

wrap = null;

}

//要等 wiewport 設置好後才能執行 refreshRem,不然 refreshRem 會執行2次;

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);

}

})(750, 750);

</script>


原文鏈接:http://caibaojian.com/simple-flexible.html

1.複製上面這段代碼到你的頁面的頭部的script標籤的最前面。·

2.根據設計稿大小,調整裏面的最後兩個參數值。

3.使用1rem=100px轉換你的設計稿的像素,例如設計稿上某個塊是100px*300px,換算成rem則爲1rem*3rem。



原文鏈接:http://caibaojian.com/simple-flexible.html

該代碼版本區別於手淘的rem換算方法。使用的是1rem=100px的換算。·

假如你有一個塊是.box{width:120px;height:80px;} 轉爲rem則爲.box{width:1.2rem; height:.8rem;}


來源:前端開發博客


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章