数据大屏自适应

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

使用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插件

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值