Vue uniapp实现图片宽度100%、高度自适应的效果

在Uniapp中,我们可以使用image组件来加载图片,而想要实现图片宽度100%、高度自适应的效果,可以通过以下步骤实现:
首先,在image组件上设置mode属性为widthFix,表示按照图片的宽度等比缩放,并保证图片宽度为100%。
接着,在image组件上设置style属性,为图片设置高度自适应。可以使用CSS的height: auto属性来实现。

<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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值