为何要在移动端使用vw做移动端适配呢?
近些年移动端的强势崛起,导致移动端适配越来越重要,个人之前一直使用的是手淘的Flexible进行适配,附上链接《使用Flexible实现手淘H5页面的终端适配》,但是发现并不是非常完美,给力的是大漠老师写了一篇《如何在Vue项目中使用vw实现移动端适配》,比较完美的解决了适配问题,下面是自己动手搭建后的一些整理。到目前为止不管是哪一种方案,都还存在一定的缺陷。言外之意,还没有哪一个方案是完美的。
事实上真的不完美?其实不然。最近为了新项目中能更完美的使用vw来做移动端的适配。探讨出一种能解决不兼容viewport单位的方案。今天整理一下,与大家一起分享。如果方案中存在一定的缺陷,欢迎大家一起拍正。
1.我用的是vue-cli4脚手架搭建的。
2.现初始化一个项目
vue create "vw-layout" ("vw-layout ---->项目名称")
cd vw-layout
npm run serve
3.安装需要的插件
npm i postcss-aspect-ratio-mini postcss-px-to-viewport postcss-write-svg postcss-cssnext postcss-viewport-units cssnano postcss-import postcss-url --S
4.还需要安装一个插件,不然会报错
npm i cssnano-preset-advanced --save-dev;
5.在根目录创建一个文件 postcss.config.js,并复制以下代码
module.exports = {
"plugins": {
"postcss-import": {},
"postcss-url": {},
"postcss-aspect-ratio-mini": {},
"postcss-write-svg": {
utf8: false
},
"postcss-cssnext": {},
"postcss-px-to-viewport": {
viewportWidth: 375, // (Number) The width of the viewport.
viewportHeight: 667, // (Number) The height of the viewport.
unitPrecision: 3, // (Number) The decimal numbers to allow the REM units to grow to.
viewportUnit: 'vw', // (String) Expected units.
selectorBlackList: ['.ignore', '.hairlines'], // (Array) The selectors to ignore and leave as px.
minPixelValue: 1, // (Number) Set the minimum pixel value to replace.
mediaQuery: false // (Boolean) Allow px to be converted in media queries.
},
"postcss-viewport-units":{},
"cssnano": {
preset: "advanced",
autoprefixer: false,
"postcss-zindex": false
}
}
}
6.在index.html引入JavaScript文件
viewport-units-buggyfill主要有两个JavaScript文件:viewport-units-buggyfill.js和viewport-units-buggyfill.hacks.js。你只需要在你的HTML文件中引入这两个文件。比如在Vue项目中的index.html引入它们:
<script src="//g.alicdn.com/fdilab/lib3rd/viewport-units-buggyfill/0.6.2/??viewport-units-buggyfill.hacks.min.js,viewport-units-buggyfill.min.js"></script>
<script>
window.onload = function () {
window.viewportUnitsBuggyfill.init({
hacks: window.viewportUnitsBuggyfillHacks
});
/* var winDPI = window.devicePixelRatio;
var uAgent = window.navigator.userAgent;
var screenHeight = window.screen.height;
var screenWidth = window.screen.width;
var winWidth = window.innerWidth;
var winHeight = window.innerHeight;
alert(
"Windows DPI:" + winDPI +
";\ruAgent:" + uAgent +
";\rScreen Width:" + screenWidth +
";\rScreen Height:" + screenHeight +
";\rWindow Width:" + winWidth +
";\rWindow Height:" + winHeight
) */
//注释代码可以看出你设备的信息,没用的,主要是上面的那一段
}
</script>
7.在img中content会引起部分浏览器下,图片不会显示。这个时候需要全局给img标签添加一个属性:
img { content: normal !important; }