rem现在是相应式开辟挪动端一个很主要也是经常使用的一个元素,但是在网上看的种种文章都邑超等懵逼。所以我在下面给出两个计划,也枚举出使用方法,让人人一览无余。条件是设想稿以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的width:750px;height:200px;
换算为rem,即为width:18.75rem,height:5rem;
此时 1rem = 40px;将设想稿标注的宽高除以40即可获得rem的值。
<div style="width:18.75rem;height:5rem;background:#f00;color:#fff;text-align:center;">
此时在iPhone6上测试,width:375px,也即width:100%。
</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的width:750px;height:200px;
换算为rem,即为width:37.5rem,height:10rem;
此时 1rem = 20px;将设想稿标注的宽高除以20即可获得rem的值。
<div style="width:37.5rem;height:10rem;background:#f00;color:#fff;text-align:center;">
test
</div>
以上两种计划均为经由过程js动态设置html的根元素的font-size的值来到达相应式的结果。
末了一个为手淘的计划:
<meta content="yes" name="apple-mobile-web-app-capable">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0, minimal-ui" />
<meta content="yes" name="apple-touch-fullscreen">
<meta content="telephone=no,email=no" name="format-detection">
<script src="http://g.tbcdn.cn/mtb/lib-flexible/0.3.4/??flexible_css.js,flexible.js"></script>
<!-- 设想稿照旧为750px,此div在视觉稿中width:750px ;height:200px;
在此计划中 1rem == 75px 也就是说视觉稿中的px值除以75即可获得rem的值。
-->
<div style="width:10rem;height:2rem;background:#f00;color:#fff;text-align:center;">
test
</div>
本文为原创文章,转载请保存原出处,轻易溯源,若有毛病处所,感谢斧正。
原文链接:经由过程js动态设置根元素的rem计划