To realize the effect of image width 100% and height self-adaptation, it can be achieved through the following steps:
1. Set the mode attribute on the image component to widthFix, which means scaling according to the width of the image and ensuring that the image width is 100%.
2. Set the style attribute on the image component, and set the height adaptive for the image; you can use the height: auto attribute of CSS to achieve.
<template>
<view class="container">
<image class="img" mode="widthFix" :src="imageUrl" :style="{ height: imgHeight + 'px' }" @load="onImgLoad" />
</view>
</template>
<script>
export default {
data() {
return {
imageUrl: 'https://picsum.photos/400/300',
imgHeight: 0,
};
},
methods: {
onImgLoad(e) {
// 当图片加载完成后,获取图片的原始宽度和高度,并根据宽度计算出高度
const { width, height } = e.mp.detail;
this.imgHeight = (height / width) * 100; // 高度 = 原始高度 / 原始宽度 * 100
},
},
};
</script>
<style>
.container {
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
.img {
width: 100%;
}
</style>
practice
<!-- 我要入驻 -->
<view class="settleIn" @click="goto('/pages/business/settleIn/settleIn')">
<image class="img" mode="widthFix" :src="settleInImageSrc" :style="{ height: imgHeight + 'px' }"
@load="onImgLoad" />
</view>
data(){
return:{
// 申请入驻图片
settleInImageSrc: "",
imgHeight: 0,
}
}
methods:{
// 图片自适应
onImgLoad(e) {
// 当图片加载完成后,获取图片的原始宽度和高度,并根据宽度计算出高度
const {
width,
height
} = e.mp.detail;
this.imgHeight = (height / width) * 100; // 高度 = 原始高度 / 原始宽度 * 100
},
}
.settleIn {
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
.img {
width: 100%;
}
Effect