方案需求:
rem 單位在做移動端的h5開發的時候是最經常使用的單位。為解決自適應的問題,我們需要動態的給文檔的根節點添加font-size 值。
使用mediaquery 可以解決這個問題,但是每一個文件都引用一大串的font-size 值很繁瑣,而且值也不能達到連續的效果。
就使用js動態計算給文檔的fopnt-size 動態賦值解決問題。
設計稿以750為准。其中測試的設計稿中標注此div的width:750px;height:200px;
方案一:
<script type="text/javascript"> window.addEventListener(('orientationchange' in window ? 'orientationchange' : 'resize'), (function() { function c() { var d = document.documentElement; var cw = d.clientWidth || 750; d.style.fontSize = (20 * (cw / 375)) > 40 ? 40 + 'px' : (20 * (cw / 375)) + 'px'; } c(); return c; })(), false); </script> <style type="text/css"> html{font-size:10px} *{margin:0;} </style>
<div style="width:18.75rem;height:5rem;background:#f00;color:#fff;text-align:center;"> 此時在iPhone6上測試,width:375px,也即width:100%。
此時 1rem = 40px;將設計稿標注的寬高除以40即可得到rem的值。 </div>
方案二:
<script type="text/javascript"> !(function(doc, win) { var docEle = doc.documentElement, //獲取html元素 event = "onorientationchange" in window ? "orientationchange" : "resize", //判斷是屏幕旋轉還是resize; fn = function() { var width = docEle.clientWidth; width && (docEle.style.fontSize = 10 * (width / 375) + "px"); //設置html的fontSize,隨着event的改變而改變。 }; win.addEventListener(event, fn, false); doc.addEventListener("DOMContentLoaded", fn, false); }(document, window)); </script>
<style type="text/css"> html { font-size: 10px; } *{ margin: 0; } </style>
<div style="width:37.5rem;height:10rem;background:#f00;color:#fff;text-align:center;"> 此時 1rem = 20px;將設計稿標注的寬高除以20即可得到rem的值。 </div>
write by tuantuan
