首页 > 解决方案 > 如何在角度材质卡中使用图片元素

问题描述

如何将图片元素与 Angular Material 卡片结合起来?

在 Angular Material 卡片https://material.angular.io/components/card/examples你可以使用<img mat-card-image src="../assets/img/shiba2.jpg" alt="Photo">

(该mat-card-image指令使图像占据卡片的整个宽度。)

但是,当我在图片和/或源元素上引入picture带有mat-card-image指令的元素时,它会破坏 CSS,并且似乎 Angular-Material 不支持该元素。

这有效,但始终显示img元素:

<picture>
    <source srcset="../assets/img/shiba2.webp" type="image/webp">
    <source srcset="../assets/img/shiba2.jpg" type="image/jpg">
    <img mat-card-image src="../assets/img/shiba2.jpg" alt="Photo">
</picture>

我想使用图片元素来使用 webp 图像并在 Safari 等不受支持的浏览器中回退到 jpg/png。

标签: htmlangularangular-material

解决方案


使用材料网站上给出的示例 stackblitz,您可以执行以下操作来获取您要查找的内容...

  <picture>
    <source media='(min-width:0px)' srcset="https://material.angular.io/assets/img/examples/shiba2.jpg">
    <img mat-card-image src="" alt="Photo of a Shiba Inu">
  </picture>

材料网站上示例 stackblitz 的相关HTML :

<mat-card class="example-card">
  <mat-card-header>
    <div mat-card-avatar class="example-header-image"></div>
    <mat-card-title>Shiba Inu (using <code>picture</code> tag)</mat-card-title>
    <mat-card-subtitle>Dog Breed</mat-card-subtitle>
  </mat-card-header>
  <picture>
    <source media='(min-width:0px)' srcset="https://material.angular.io/assets/img/examples/shiba2.jpg">
    <img mat-card-image src="" alt="Photo of a Shiba Inu">
  </picture>
  <mat-card-content>
    <p>
      The Shiba Inu is the smallest of the six original and distinct spitz breeds of dog from Japan.
      A small, agile dog that copes very well with mountainous terrain, the Shiba Inu was originally
      bred for hunting.
    </p>
  </mat-card-content>
  <mat-card-actions>
    <button mat-button>LIKE</button>
    <button mat-button>SHARE</button>
  </mat-card-actions>
</mat-card>

推荐阅读