自适应:为了兼容不同的屏幕尺寸
响应式:不仅是兼容屏幕尺寸,还要兼顾样式上的等,包含的内容比自适应更多
因为是纯静态页面,使用淘宝无线适配的方案。
下载lib-flexible,postcss-pxtorem
使用lib-flexible利用dpr(物理像素和css像素比),计算出像素比,保证在不同的设备会根据不同的像素比展示元素的大小。给根元素设置font-size属性,这样使用项目中使用px像素就不管用了。
引入lib-flexible之后,需要修改index.html里的代码。
<!--移动端适配-->
<meta
name="viewport"
content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, minimal-ui, viewport-fit=cover,user-scalable=no"
/>
<!---不使用远程的包,使用本地的包->
<!-- <script src="http://g.tbcdn.cn/mtb/lib-flexible/0.3.2/??flexible_css.js,flexible.js"></script> -->
<script src="./public/js/flexible.js"></script>
此时,postcss-pxtocss登场,将项目中的px像素自动转换为rem像素。
PS:写在内联中的样式px不会进行转换。解决方法:利用动态绑定class属性来实现。
postcss-pxtorem配置:
const px2rem = require('postcss-pxtorem');
module.exports = {
plugins: [
px2rem({
rootValue: 192, //设计稿宽度
unitPrecision: 5,
propList: ['*'],
exclude: /(node_module)/,//排除node_modules下的样式转换
}),
],
};
举个例子:
<!---之前我们使用动态style绑定样式-->
<div :style="{
transform: `translateX(${drawerLeft ? '0px' : '278px'})`,
}"></div>
<!---现在我们这样使用-->
<div :class="drawerLeft ? 'translate278' : 'translate0'"></div>
<style>
.translate278 {
transform: translateX(278px);
}
.translate0 {
transform: translateX(0px);
}
</style>
遇到的坑:
-
px2css不生效问题
原先项目中有使用postcss,导致这两个包冲突。解决:有卸载px2css,安装pxtocss。 -
根元素字体大小一直为54px问题:
修改lib-flexible.js源码,源码上设置元素最大超过540之后,一直按照540来计算,540/10就是54px,跟元素即html fontSize大小为54px。
function refreshRem(){
var width = docEl.getBoundingClientRect().width;
// if (width / dpr > 540) {//原来的
// width = 540 * dpr;
// }
var rem = width / 10;
docEl.style.fontSize = rem + 'px';
flexible.rem = win.rem = rem;
}
- node_modules里面得代码修改完不生效问题
使用patch-packages,参考
如果你是使用的vue项目,在main.js中安装lib-flexible之后,引入即可。
但是又引入一个问题,node环境中不支持window属性,因此需要把这个包下载下来下载链接,放在public目录下,在Index.html中使用相对路径进行引入即可。
如何验证:
![](https://img.haomeiwen.com/i10131721/07ec4379da8edc44.png)
![](https://img.haomeiwen.com/i10131721/339ab700686fc2cd.png)
保留问题:
pxtorem设置的rootValue不能动态修改吗?这样无论是使用pc端设计稿还是移动端设计稿都可以很好进行适配。
目前还没发现解决方案,因为发现修改了pxtorem配置之后需要重新npm run dev才可以。
网友评论