使用scale方式进行屏幕缩放实现适配大屏。无需特定编写rem,也不用考虑单位不一致导致的适配无效(%px随便用)。
原理:当我屏幕大小与设计稿大小不符的时候,计算缩放的比例,从而设置盒子的scale属性。
实例:Vue2用户可直接复制代码看看。react或angular用户参考示例琢磨一下
<template>
<div class="box">
<div class="screen" id="screen">
<div class="contain-box">
<div>
侧边栏
</div>
<div>
<header>这是头部</header>
<section>这是身体</section>
<footer>这是脚</footer>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
mounted() {
this.handlerScale()
window.onresize = () => this.handlerScale();
},
methods: {
handlerScale(){
let designWidth = 1920; //设计图的宽度
let designHeight = 620; //设计图的高度
const scale = document.documentElement.clientWidth / document.documentElement.clientHeight < designWidth / designHeight
? (document.documentElement.clientWidth / designWidth)
: (document.documentElement.clientHeight / designHeight)
document.getElementById('screen').style.transform = `scale(${scale}) translate(-50%)`
}
},
destroyed() {
window.onresize = null;
},
}
</script>
<style lang="less" scoped>
.box{
width: 100%;
height: 100%;
.screen{
width: 1920px;
height: 100px;
transform-origin: 0 0;
position: absolute;
left: 50%;
}
.contain-box{
display: flex;
>div:first-of-type{
width: 200px;
background-color: purple;
}
>div:last-of-type{
flex: 1;
}
}
}
header{
width: 100%;
background-color: pink;
}
section{
width: 100%;
background-color: greenyellow;
}
footer{
width: 100%;
background-color: red;
}
</style>