移动端适配

移动端适配方案:

有三种:分别是手写rem、插件安装、vw和vh

rem的概念:

rem是指相对于根元素的字体大小的单位,1rem等于html根元素font-size的px值

手写rem布局:

<div class='head'>头部</div>
<style>
	.head {
		width:7.5rem;
		height:0.88rem
	}
</style>
<script>
	rem()
	// 页面大小发生变化就会触发这个函数
	window.onresize = function () {
		rem()
	}
	function rem() {
		// 获取html的宽度
		let hh = document.documentElement.clientWidth
		// 获取body的宽度
		let bh = document.body.clientWidth
		// 让宽度 赋值为 html或者body的宽度 
		// IE浏览器认为body为最大的 而其他的浏览器认为html为最大的
		let h = hh || bh
		// 给html设置动态的fontSize属性
		document.documentElement.style.fontSize = (h / 750 * 100) + 'px'
	}
</script>

 

rem适配方案

推荐使用以下两个工具:
postcss-pxtorem 是一款 postcss 插件,用于将单位转化为 rem
lib-flexible 用于设置 rem 基准值(设置1rem等于多少px)

安装依赖

cnpm install lib-flexible postcss-pxtorem --save-dev

在main.js中导入

 import 'lib-flexible/flexible'; 

 

postCss配置:
创建.postcssrc.js
这是个基础的,有需要的可以自行修改

module.exports = {
  plugins: {
    autoprefixer: {
      overrideBrowserslist: ['Android 4.1', 'iOS 7.1', 'Chrome > 31', 'ff > 31', 'ie >= 8']
    },
    'postcss-pxtorem': {
      rootValue: 75,
      propList: ['*']
    }
  }
}

因为我们用了 Vant 的组件,需要按照 rootValue: 37.5 来写样式
注意

这里会报错 postCss 需要8的版本(但是postCss 还没有8的版本)
所以这里建议对postcss-pxtorem进行降级

降级命令 npm install postcss-pxtorem@5.1.1 --save


vw和vh

vw 是视图宽度
vh 是视图高度
100vw 就是全屏的宽度


安装依赖

npm install postcss-px-to-viewport -D

注释原来的rem代码

import 'lib-flexible/flexible.js'

"lib-flexible": "^0.3.2",
"postcss-pxtorem": "^5.1.1",

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值