效果演示
代码
<template>
<view class="content">
<!-- 背景图片 -->
<image src="/static/employeeArea/hallBg.png" mode="widthFix" class="hallBg"></image>
<view class="main">
<!-- logo -->
<view class="logo">
<image src="/static/employeeArea/hallLogo.png" mode="widthFix"></image>
</view>
<!-- 二维码 -->
<!-- 外层盒子的高度与宽度保持一致,即为正方形 -->
<view class="qrcode " id="qrcode" :style="{height: widthImg + 'px'}">
<image src="/static/employeeArea/hallCode.png" mode="aspectFill"></image>
</view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
widthImg: ''
}
},
onReady() {
let query = uni.createSelectorQuery().in(this);
query.select('#qrcode').boundingClientRect(data => {
console.log(data)
//获取元素的宽度
this.widthImg = data.width
}).exec();
},
methods: {
}
}
</script>
<style lang="scss">
.content {
width: 100%;
height: 100vh;
overflow: hidden;
}
.hallBg {
width: 100%;
height: 100%;
}
.main {
position: fixed;
top: 30%;
left: 50%;
width: 100%;
transform: translate(-50%, -30%);
.logo {
margin-left: 50%;
transform: translateX(-50%);
width: 33%;
image {
width: 100%;
}
}
.qrcode {
position: relative;
left: 50%;
top: 50%;
transform: translatex(-50%);
width: 70%;
background: #FFFFFF;
padding: 44rpx;
box-sizing: border-box;
image {
width: 100%;
height: 100%;
}
}
}
</style>
思想
我们需要一个正方形容器,内置padding,然后让里面的图片100%显示,难点在于,宽度我们直接设置为屏幕的百分之多少就行,问题就在于不同设备解析出来的宽度不同,那我们的高度不能设为死值,设为死值就变形了。我们可以动态获取元素的宽度,只要让元素的高度 = 宽度 ,元素就是正方形的状态。
onReady() {
let query = uni.createSelectorQuery().in(this);
query.select('#qrcode').boundingClientRect(data => {
console.log(data)
//获取元素的宽度
this.widthImg = data.width
}).exec();
},
网址:
https://uniapp.dcloud.net.cn/api/ui/nodes-info.html#createselectorquery