项目在移动端做适配,用户还要求web版从电脑端打开网址时,也显示为手机的竖屏样式。故选择固定宽高度方式,计算每个元素的大小。
1.在app.vue中,获取设备的宽高,设置页面的初始高度
<div id="app"
:style="{height:bodyHeight + 'px'}"
:class="flagPc ? 'pc-width':'phone-width'">
<router-link to="/"></router-link>
<router-view/>
</div>
data() {
return {
flagPc:false,
bodyHeight: 0
}
},
mounted() {
this.init();
},
methods:{
/**
* 判断手机端还是电脑端,并设置宽度和高度
*/
init() {
let userAgentInfo = navigator.userAgent;
let Agents = ["Android","iPhone","SymbianOS","Windows Phone","iPad","iPod"]
this.flagPc = true;
for (let v = 0; v < Agents.length; v++) {
if (userAgentInfo.indexOf(Agents[v]) > 0) {
this.flagPc = false;
break;
}
}
if (this.flagPc) { //PC端
console.log('pc')
this.bodyHeight = 812;
document.documentElement.style.setProperty('--body-height', '812px')
document.documentElement.style.setProperty('--body-width', '375px')
} else { //手机端
console.log('手机')
let height = document.documentElement.clientHeight
let width = document.documentElement.clientWidth
this.bodyHeight = height;
document.documentElement.style.setProperty('--body-height', height + 'px')
document.documentElement.style.setProperty('--body-width', width + 'px')
}
}
}
#app {
font-family: Arial, Avenir, Helvetica, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-size: 16px;
color:#333;
}
.pc-width {
width: 375px;
margin:0 auto;
}
.phone-width {
width: 100%;
}
2.在公共样式文件(common.css)中设置变量
:root {
--body-height: 0;
--body-width: 0;
}
3.在页面中使用变量
.a {
width: calc(0.44 * var(--body-width));
}
.b {
height: calc(var(--body-height) - 140px);
}
vue项目做手机端项目,用的是vant2插件:https://vant-ui.github.io/vant/v2/#/zh-CN/field。