设置HTML的font-zise,使rem更好的兼容移动端

现在使用PX都不怎么适应手机端,自从有了rem之后,彻底告别px,rem的大小是随着HTML的font-size打大小来决定的,所以,在不同宽度的设备,用JS改变html的font-size就可以完美的使用rem了。



可以直接复制我下面那段html来预览demo。

1rem = html的font-size的大小




<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script>
//设置HTML的font-zise
(function (doc, win) {
  var docEl = doc.documentElement,
	resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
	recalc = function () {
	  var clientWidth = docEl.clientWidth;
	  if (!clientWidth) return;
	  docEl.style.fontSize = 20 * (clientWidth / 320) + 'px';
	};

  if (!doc.addEventListener) return;
  win.addEventListener(resizeEvt, recalc, false);
  doc.addEventListener('DOMContentLoaded', recalc, false);
})(document, window);
//end	
</script>
</head>

<body>

<p style="font-size:0.5rem">html的font-size会随着窗口大小变化而改变, JS就上面那一段而已。</p>
<p style="font-size:0.5rem">1rem = html的font-size</p>

<button style=" padding:0.2rem 0.5rem; background:#eee; font-size:0.6rem">我是按钮</button>



</body>
</html>




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值