rem做到pc端到移动端自适应

8 篇文章 0 订阅
6 篇文章 0 订阅
// 默认rem换算px 1rem = 16px
const defSize = 16;
// 默认px换算rem比率 
const defPxRatio = 1 / defSize;
// 默认px换算rem 100倍比率
const tallNum = defPxRatio * 100;
// 默认浏览宽度 1920 宽度下html font-size为6.25% 用于计算1920上下范围自适应
// 可以自行调整宽度,需要注意的是一些浏览器在太小的浏览器宽度下不进行计算了(欢迎解释)
// 比如谷歌设置1280下明显html font-size不管用
const defWidth = 1920;
// 默认宽度百分比
const defRatio = 100 / (defWidth / defSize);
// 当前使用浏览器
const browser = navigator.userAgent.toLowerCase();
const adaptive = (doc, win)=> {
	const docEl = doc.documentElement,
		resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
		recalc = () => {
			const clientWidth = docEl.clientWidth;
			if (!clientWidth) return;
				// 即时获取宽度百分比
				const ratio = clientWidth / defSize;
                // 即时换算比率 即时宽度百分比 * 默认宽度百分比 * px换算rem比率
				const fontSize = ratio * defRatio * defPxRatio;
				// 如果是谷歌内核并且fontSize高于px换算rem比率则固定为该比率
				if(browser.indexOf('chrome') > -1 && fontSize < tallNum){
					docEl.style.fontSize = `${tallNum}%`
				}else{
					// 更改html fontSize
					docEl.style.fontSize = `${fontSize}%`;
				}
			};
		if (!doc.addEventListener) return;
		win.addEventListener(resizeEvt, recalc, false);
		doc.addEventListener('DOMContentLoaded', recalc, false);
}
// 初始化
adaptive(document, window);
//随浏览器大小自适应
window.onresize = function() {
	adaptive(document, window);
}

以rem为单位或百分比。

经过换算现在1rem = 1px 所以放心的用ui给的px像素单位值都是 1:1 的

  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值