1. js文件:
function recalc(x,bol) {
var clientWidth = document.body.clientWidth;
if (bol && (!clientWidth || clientWidth > x)) {
document.documentElement.style.fontSize = "";
return;
};
document.documentElement.style.fontSize = 100 * (clientWidth / x) + 'px';
};
var remCompute = function (width,device) {
if (window.addEventListener) {
recalc(width,device);
var resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize';
window.addEventListener(resizeEvt, function () {recalc(width,device)}, false);
};
};
// NOTE:
// html页面body下的最上方引入方法
// width: 预设宽度/预设响应的时机;
// device:true(pc) false(mobile)
// =ture时 **pc做响应式时只有在小于width时才计算**
// =false时 **mobile端随时都进行计算**
// 方法: remCompute(640,false);
// 换算方法: 100px = 1rem; 例如20px = 0.2rem;
2. 页面引入:
<script src="js/rem.js" charset="utf-8"></script>
<script type="text/javascript">
remCompute(900, true); //900是浏览器小于多少的时候开始将px转化为rem
</script>
3. CSS:
body{ color: #fff; font-size: 16px; width: 100%; min-width: 1903px; font-family:-apple-system,"Source Sans Pro","Noto Sans CJK SC","PingFang SC","Segoe UI","Microsoft YaHei",Sans-Serif,Helvetica,Arial; }
@media (max-width:900px){
body{ min-width: auto; font-size: 0.16rem; background-color: #070c2b}
}
* 注意:
不要给html / body设置最大或最小宽度,会影响换算。