如何保留几张不同的照片文件并根据屏幕大小选择一个作为背景?

问题描述 投票:0回答:2

从我的.html文件中的类似内容开始:

<mat-sidenav-content
    [ngStyle]="{'background-image': 'url(' + backgroundImageURL + ')',
        'background-size': backgroundSize, 'background-repeat': backgroundRepeat,
         'background-position': 'center center'}">
</mat-sidenav-content>

其中backgroundImageURLbackgroundSizebackgroundRepeat是我在“ environment.ts”文件中定义的变量,

我如何保留3个不同的图像文件(例如_- small__ medium__ large),然后根据屏幕尺寸应用其中一个或另一个?

谢谢。

angular background-image
2个回答
0
投票

例如,您可以轻松地使用吸气剂进行此操作:

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是内置的。


0
投票

您应该执行ts文件。

 let image = 'myImage';

 if (window.innerWidth < 420) {
     image += '-small';
 } else if (window.innerWidth < 768) {
     image += '-medium';
 } else {
     image += '-large';
 }

 this.backgroundImageURL  = image;
© www.soinside.com 2019 - 2024. All rights reserved.