uni-app中,图片在容器水平垂直居中

37 阅读1分钟

图片image的尺寸宽、高小于300rpx,居中显示

图片image的尺寸宽、高大于300rpx,缩放显示

 <view
  class="goods_card"
  v-for="(item, index) in goodsList"
  :key="index">
  <view class="goods_img_placeholder">
    <image
      class="img"
      :src="item.imageUrl"
      :mode="modeList[index] || 'aspectFit'"
      @load="loadEnd($event, index)" />
  </view>
</view>
.goods_img_placeholder {
    width: 300rpx;
    height: 300rpx;
    background-color: #eee;
    position: relative;
    .img {
      width: 100%;
      height: 100%;
    }
}
<script setup>
import { ref, inject } from "vue";
let goodsList = ref([]);
let modeList = ref([]);
let w = ref(0);
let h = ref(0);


function loadEnd(e, index) {
  if (w.value) {
    if (e.detail.width > w.value || e.detail.height > h.value) {
      modeList.value[index] = "aspectFit";
    } else {
      modeList.value[index] = "center";
    }
  } else {
    const query = uni.createSelectorQuery();
    query
      .select(".goods_img_placeholder")
      .boundingClientRect((res) => {
        if (res) {
          w.value = res.width || 0;
          h.value = res.height || 0;
          console.log("宽高:", w.value, h.value);
        } else {
          console.log("未找到目标view");
        }

        if (e.detail.width > w.value || e.detail.height > h.value) {
          modeList.value[index] = "aspectFit";
        } else {
          modeList.value[index] = "center";
        }
      })
      .exec(); // 执行查询
  }
}
</script>

效果图