首页 > 解决方案 > 带有 Web 组件图像的图像网格布局

问题描述

我的目标是为一组图像实现这种布局:

在此处输入图像描述

正如您所看到的,一个简单的 2 列方形图像网格 - 这在 Bootstrap 环境中非常容易,其中一个指定 2 列或每个大小 6,然后只需将图像的 CSS 设置object-fit为覆盖以避免拉伸和设置高度自动。

问题是,我试图在 Ionic 4 中实现这一点,其中 img 元素是一个 Web 组件,只有某些属性可以自定义。到目前为止,我可以让图像以 2 列的方式显示,但纵横比已关闭。(我也必须使用该元素,所以不能简单地使用 HTML5 img 元素)。

这是我到目前为止所拥有的:

    <ion-grid>
        <ion-row>
            <ion-col size="6" *ngFor="let image of selectedImageURIs">
                <ion-img [src]="image"></ion-img>
            </ion-col>
        </ion-row>
    </ion-grid>

注意:Ionic 框架有它自己的“Bootstrap”框架,称为 ion-grid。我最终得到的是:

在此处输入图像描述

我知道需要使它们的高度相同,并且将对象设置为适合覆盖,但是如何使用 ion-img 来做到这一点?I 是一个 Web 组件,因此 Shadow Dom 发挥了作用。文档只是提到"The component uses Intersection Observer internally". 那能做我需要的吗?我是 Web 组件的新手,试图了解我所缺少的内容。

标签: ionic-frameworkionic4web-componentshadow-dom

解决方案


这是我用于 Ionic 4 应用程序的解决方案。我使用 css 来完成您想要的外观。您的模板将看起来像这样,并ion-img用于利用延迟加载功能。

html

<ion-grid>
  <ion-row>
    <ion-col *ngFor="let category of categories" size="6">
      <button #categoryButton type="button" (click)="selectCategory(categoryButton, category)" class="category-button">
        <ion-card padding class="category-card">
          <ion-card-content class="category-card-content">
            <ion-img *ngIf="!imageNotLoaded; else loadingCategory" src="{{category.icon_image}}" class="category-icon" (ionError)="imageNotLoaded = true"></ion-img>
            <ng-template #loadingCategory>
              <ion-skeleton-text animated style="height: 70px;width: 70px"></ion-skeleton-text>
            </ng-template>
          </ion-card-content>
          <ion-card-title class="category-title">{{category.name}}</ion-card-title>
        </ion-card>
      </button>
    </ion-col>
  </ion-row>
</ion-grid>

像这样设置你的 sass 代码。

scss

ion-col {
  text-align: center;
}

.active {
  .category-card {
    border-color: var(--ion-color-primary)!important;
    box-shadow: 0 4px 16px var(--ion-color-primary)!important;
  }
}

.category-button {
  padding: 4px;
  background: transparent;
  .category-card {
    min-width: 100%;
    margin: 0;
    border: 2px solid;
    .category-card-content {
      text-align: center;
      .category-icon {
        width: available;
      }
    }
    .category-title {
      font-size: x-small;
      font-weight: bolder;
    }
  }
}

然后产生如下图所示的最终结果。

注意:这是所有组件级代码,否则您需要使用::ng-deep它来绕过 css 代码的影子 dom。

使用 ion-grid 和 ion-img 进行网格显示


推荐阅读