angular - 如何保留多个不同的照片文件并根据屏幕大小选择一个作为背景?
问题描述
从我的 .html 文件中的类似内容开始:
<mat-sidenav-content
[ngStyle]="{'background-image': 'url(' + backgroundImageURL + ')',
'background-size': backgroundSize, 'background-repeat': backgroundRepeat,
'background-position': 'center center'}">
</mat-sidenav-content>
wherebackgroundImageURL
和是我在“environment.ts”文件中定义的变量backgroundSize
,backgroundRepeat
如何保留 3 个不同的图像文件(例如_-small、_-medium、_-large),并根据屏幕尺寸应用其中一个或另一个?
谢谢。
解决方案
您可以使用例如 getter 轻松做到这一点:
get backgroundImgUrl() {
if (window.innerWidth > 1000) {
return 'http://path-to-image.jpg';
} else ...
}
但是您应该使用 srcset 属性:https ://developer.mozilla.org/fr/docs/Apprendre/HTML/Comment/Ajouter_des_images_adaptatives_%C3%A0_une_page_web是内置的 html。