剛開始做移動端的開發的時候,大多時候是在使用 像素(PX)來寫頁面和布局的,但是使用下來,還是有多少不好用!
隨之就開始用 rem 來寫,rem寫的結果是頁面放到一些屏幕上,字體過小,如果頁面渲染用了rem,但是網站后台編輯器里的字體大小是用像素來做的,這就可能出現一種情況,rem設置的像素要比編輯器里設置的像素要小很多,所以所有的都用 rem 來設置大小,還是有些許問題。
互聯網技術,想來想去還是看看阿里是怎么做的?打開淘寶的手機端,他使用的 px+rem混合做的,經過測試確實這種比較好!
下面就具體說下兩種 rem 設置大小的方法:
第一種:按照設計稿750的大小來設置:
<style type="text/css"> html{font-size:100px;} </style> <script type="text/javascript"> var winW = $(window).width(); if (winW > 750) {winW = 750;} $('html').css('font-size', winW / 7.5); $(window).resize(function () { winW = $(window).width(); if (winW > 750) {winW = 750;}; $('html').css('font-size', winW / 7.5); }); </script>
設置html的大小為100px,那么頁面的 750px 就相當於是 7.5rem; 100px 就是 1rem;1px就是0.01rem;也就是頁面上多少像素,轉化為 rem 就是除以100 即可;
第二種:按照設計稿540的大小來設置:(淘寶的做法)
<style type="text/css"> html{font-size:54px;} </style> <script type="text/javascript"> var winW = ""; $(window).resize(function(){partCom();}); partCom(); function partCom(){ winW = $(window).width(); $('html').css('font-size', winW / 10); }; </script>
設置html的大小為54px;540px就是10rem;54px等於1rem;1px等於1/54像素;這種做的話,多少像素就必須計算出多少rem;
<style type="text/css"> div.jisuan{width: 100%; height:1.4814rem; line-height: 0.6296rem; background:rgba(0,0,0,0.5); position: absolute; top:0px; font-size:12px;} div.jisuan input{width: 1.8518rem; height: 0.5555rem; line-height: 0.5555rem; font-size:16px; text-indent: 0.1851rem; border:none; outline: none;} div.jisuan input.px{margin-left: 0.5555rem;} div.jisuan span.dy{font-size:14px; color:#fff;} div.jisuan span.px{font-size:24px; color: #fff;} </style> <div class="jisuan"> <div class="pxtorem"> <input type="text" class="px" value="540"> <span class="px">px</span> <span class="dy">=</span> <input type="text" class="rem" value="10"> <span class="px">rem</span> </div> <script> (function(){ /* 計算 540px = 10rem 1px = (10/540) rem */ $("div.pxtorem input.px").blur(function(){ $("div.pxtorem input.rem").val(Math.round($("div.pxtorem input.px").val()*(10/540)*10000)/10000); }); })(); </script> <div class="remtopx"> <input type="text" class="px" value="10"> <span class="px">rem</span> <span class="dy">=</span> <input type="text" class="rem" value="540"> <span class="px">px</span> </div> <script> (function(){ /* 計算 10rem = 540px 1rem = (540/10) px */ $("div.remtopx input.px").blur(function(){ $("div.remtopx input.rem").val(Math.round($("div.remtopx input.px").val()*(540/10)*10000)/10000); }); })(); </script> </div>
總結:總的來說,第一種方法更加方便,也可以用;但是更推薦第二種,參考淘寶的做法來寫移動打的頁面;