做移动端的项目,最重要的就是页面的自适应。比如让一个子盒子在父盒子中按照一定的比例缩放居中显示,以便整个子盒子能最大程度的显示在手机上,而不变形。
之前用过用padding来计算,但是不太准确,所以这次就用js来计算,主要是要了解到background-size中contain的计算方式,由于篇幅太长,可以详细了解的,参考https://www.w3cplus.com/css3/background-size-for-contain-and-cover.html
我现在就直接上代码
// 动态计算div的宽高来按照一定的比例自适应
computeWH(w, h, box_width, box_height, edit_box_dom) {
const scale = w / h; // 比例
if (scale <= box_width / box_height) {
edit_box_dom.style.width = `${box_height * scale}px`; // 计算宽
edit_box_dom.style.height = `${box_height}px`; // 计算高
} else {
edit_box_dom.style.width = `${box_width}px`;
edit_box_dom.style.height = `${box_width / scale}px`;
}
},
在vue中的使用方法:
<template>
<div class="box" ref="box">
<div class="view" ref="view">9090</div>
</div>
</template>
<script>
export default {
name: "home",
mounted() {
this.computeWH(
1080, // 比例-宽
1920, // 比例-高
this.$refs.box.clientWidth, // 父盒子的宽度
this.$refs.box.clientHeight, // 父盒子的高度
this.$refs.view // 子盒子元素
);
},
}
</script>
<style lang="scss">
.box{
min-hight: 100vh;
.view {
margin: 0 auto;
}
}
</style>
效果:
保持海报在比例9:16下,div一直居中显示,其余部分就留白,保证中间部分按比例不拉伸变形