写一个js配合rem
目前笔者解决移动端的尺寸带来的样式问题,都是通过viewport + rem的。viewport 相信大家都用过了,而rem需要用js动态设置html的字体大小。
动态设置rem的根字体大小首先我们要确定你的设计稿大小是多少,一般移动端设计稿的宽度是750,当然也用些用1080的;
我们要确定rem和px的转换比例,前提是要注意浏览器的字体大小是有限制的,,比如chrome的字体不能小于12px;
记得加上viewport,比如这样设置:<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">;
/** * design: 是设计稿的宽度,也是页面的最大宽度 * 这里的比例是1:100; 1rem = 100px; **/ function setRem(design=750){ let styleElm = document.createElement('style'); rem(); document.firstElementChild.appendChild(styleElm); window.onresize = function(){ rem(); } function rem(){ let winWidth = document.documentElement.getBoundingClientRect().width; winWidth = Math.min(winWidth,design); let fontSize = winWidth / design *100; document.body.style.fontSize = '16px'; styleElm.innerHTML = 'html {font-size:'+fontSize+'px;}'; } }写一个js配合rem
温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/41432.html