适配问题如果是大屏,等比例从本地小屏电脑投放到大的显示台,而有的项目布局有屏幕横屏竖屏、平板和手机应用适配问题,比如网易云适配:
媒体查询 + rem
移动端适配问题:
假设UI给的设计稿屏幕宽度是是750px,
假设把屏幕分为15等份,每一份作为字体的font-size大小,也就是50px,
如果去适配320px设备,字体大小就是 320/15=21.33px,如果一个宽高是100px*100px的盒子,转化为rem就是100/50=2rem,即2rem*2rem
计算公式:某个盒子的rem值 = UI图某个盒子的px值 / (UI图屏幕宽度 / 划分的分数)
且UI图屏幕宽度 / 划分的分数 就是 根元素fontSize 的大小
1rem = html中的根元素fontSize 的大小
...
<body>
<div></div>
<h1></h1>
</body>
<style>
/* 注意and后面的空格不能省略,且这个两个媒体查询顺序不能瞎写 */
@media screen and (min-width:320px) {
/* 大于等于320px */
html {
font-size: 21.33px;
/* 320 / 15 = 21.33 */
}
}
@media screen and (min-width:750px) {
/* 大于等于750px */
html {
font-size: 50px;
/* 750 / 15 = 50 */
}
}
div {
width: 2rem;
height: 2rem;
background-color: yellow;
color: red;
}
</style>
...
...
<script>
function getVal() {
let dom = document.getElementsByTagName('div')[0]
let h1 = document.getElementsByTagName('h1')[0]
// 注意: js不能获取内联样式的值
h1.innerHTML = `${dom.clientWidth}px * ${dom.clientHeight}px`
}
window.onload = () => {
getVal()
}
window.onresize = () => {
getVal()
}
</script>
...
效果图如下:
由图可知:
①在小于320px的宽度情况下,因为没有规定这个范围的值,所以width和height用了默认的font-size:16px,即32px * 32px
②在大于等于320px的宽度情况下,使用了我们的适配方案,即42.66px * 42.66px
③在大于等于750px的宽度情况下,使用了我们的适配方案,即100px * 100px,上面的步骤是通过改变font-size来适配rem。
postcss-pxtorem插件
PC端适配PC大屏: ① vue2项目利用 postcss-pxtorem 将 px 转 rem;
② 监听窗口缩放事件,根据窗口大小重置浏览器根字体大小。
步骤1:下载 postcss-pxtorem 包
npm i postcss-pxtorem@5.1.1 --save-dev
步骤2:在根目录新建 postcss.config.js文件,配置 postcss-pxtorem
module.exports = {
'plugins': {
// to edit target browsers: use "browserslist" field in package.json
'autoprefixer': {},
'postcss-pxtorem': {
rootValue: 16, // 结果为:设计稿元素尺寸/16,比如元素宽320px,最终页面会换算成 20rem
propList: ['*']
}
}
}
步骤3:在 src > libs 文件夹中新建 rem.js 文件
// 设置 rem 函数
function setRem() {
// 1920 默认大小16px; 1920px = 120rem ;每个元素px基础上/16
const screenWidth = 1920
const scale = screenWidth / 16
const htmlWidth = document.documentElement.clientWidth || document.body.clientWidth
// 得到html的Dom元素
const htmlDom = document.getElementsByTagName('html')[0]
// 设置根元素字体大小
htmlDom.style.fontSize = htmlWidth / scale + 'px'
// scale比率 = 假想设计图的宽度 / (假想设计图font-size),即 假设: 1920 / 16
// 注意:scale比率 不等于 1rem
// 则:屏幕字体大小 = 屏幕宽度750px / scale比率 ,即 htmlDom.style.fontSize = htmlWidth / scale + 'px'
}
// 初始化
setRem()
// 改变窗口大小时重新设置 rem
window.onresize = function() {
setRem()
}
步骤4:在 main.js 文件中引入
import '@/libs/rem.js'
效果图如下:
由图可知:在手机端和PC端的尺寸比例不变,大小都是rem适配的,这个方案按照UI图比例直接在style文件中写px即可,自动将css中的px转换成rem(真的是大大提升了我们的工作效率,不用自己去瞎算)。如果你不想用 16 来算,需要把rem.js文件的16和postcss.config.js文件的16统一改,上面的步骤是通过改变font-size来适配rem。
flex.js插件
postcss-plugin-px2rem 插件 等等
这个插件配置选项上有 exclude 属性,可以配置 是否对 某个文件夹下的所有css文件不进行从px到rem的转换