最近做了个网站,关于网页适配不同电脑屏幕踩了几个坑,这里记录一下;
代码可以直接复制使用:
<template>
<div ref="body" class="container">
<div class="main"></div>
</div>
</template>
<script>
import badySize from '@/mixins/bodySize'
export default {
mixins:[badySize]
}
</script>
<style lang="less" scoped>
.container {
height: 100%;
.main {
transform-origin: left top;
position: relative;
width: 1920px;
height: 100%;
}
}
</style>
export default {
data() {
return {
mainStyle: "",//对main设置动态样式
};
},
watch: {
mainStyle: {
handler() {
//把动态样式绑定到节点上
this.$refs["body"]
.querySelector(".main")
.setAttribute("style", this.mainStyle);
},
},
},
async mounted() {
await this.$nextTick();
if (this.$refs["body"]) {
let scale_x = this.$refs['body'].clientWidth / 1920;
let h = (100 / scale_x).toFixed(2);
//这里增加了一个height,防止因为宽高比例和1920:1080不一致导致底部出现空白
this.mainStyle = `transform: scale(${scale_x});height:${h}%;`;
}
window.addEventListener("resize", () => {
setTimeout(() => {
if (this.$refs["body"]) {
console.log("this.$refs['body'].clientWidth", this.$refs['body'].clientWidth)
let scale_x = this.$refs['body'].clientWidth / 1920;
let h = (100 / scale_x).toFixed(2);
this.mainStyle = `transform: scale(${scale_x});height:${h}%;`;
}
})
});
},
};
这里使用了混入,在使用时在html中要在最外层div添加ref='body',第二层div添加class='main';我这边的标准尺寸是1920:1080;如果不是这个尺寸,请在对应的文件中修改为对应的尺寸
我已经对不同的屏幕尺寸做了验证,基本上满足情况