本文转自@工边页字,仅供自己学习使用,侵权立即删除

使用rem进行自适应需要注意单位,采用scale实现完全自适应,但是仅限于固定宽高比


const initScreen = () => {
	const designWidth = 1920
	const designHeight = 960
	const currentScale = document.documentElement.clientWidth / document.documentElement.clientHeight
	const requiredScale = designWidth / designHeight
	//当前宽高比小于设计稿时,无法完全显示页面,使用scale进行缩小
	const scale = currentScale < requiredScale ?  document.documentElement.clientWidth/designWidth : document.documentElement.clientHeight/designHeight
	
	document.querySelector('#screen').style.transform =  `scale(${scale}) translate(-50%)`;
	
}

useEffect(()=> {
	initScreen()
	window.onresize = () => initScreen()
	return () => window.onresize = null
}, [])
<div c;assName='wrapper'>
	<div className='screen' id='screen'></div>
</div>
.wrapper {
	height: 100%;
	width: 100%;
	.screen {
		display: inline-block;
		width: 1920px;
		height: 960px;
		transform-origin: 0 0;
		position: absolute;
		left: 50%;
	}
}

问题

  • 缩放比例过大,字体会模糊
  • 缩放比例过大,事件触发区域会偏移

移动端适配

  • 自适应:根据不同的设备屏幕大小来自动调整尺寸、大小
  • 响应式:随着屏幕实时变动而自动调整

适配方案

  • 百分比设置(不推荐)
  • rem单位+动态html中的font-size
  • vw单位
  • flex弹性布局

rem+动态设置font-size

将px像素值转换成rem:postcss-pxtorem插件

module.exports = {
	plugins: {	
		"postcss-pxtorem": {
			rootValue: 75,	// 设计稿宽度的1/10
			propList: ["*"]		// 需要做转化处理的元素
		}			
	}
}

方案一:媒体查询

// 宽度大于320px时设置字体大小为20px
@media screen and (min-width: 320px) {	
	html {
		font-size: 20px	
	}	
}

方案二:监听屏幕尺寸变化动态修改html的font-size大小

function pxtorem(){
	const html = document.documentElement
	const htmlWidth = html.clientWidth / 10
	html.style.fontSize = htmlWidth + 'px' 
}

window.addEventListener('resize', pxtorem)

vw相比于rem的优势

  • 不需要计算html的font-size大小
  • 不需要必须给body设置一个font-size防止继承
  • 不用担心html的font-size被篡改导致页面尺寸混乱

vw和px单位转化

使用postcss-px-to-viewport-8-plugin插件

Logo

永洪科技,致力于打造全球领先的数据技术厂商,具备从数据应用方案咨询、BI、AIGC智能分析、数字孪生、数据资产、数据治理、数据实施的端到端大数据价值服务能力。

更多推荐