如何保留多个不同的照片文件并根据屏幕大小选择一个作为背景?
How to keep several different photos files and choose one as background based on screen size?
从我的 .html 文件中的类似内容开始:
<mat-sidenav-content
[ngStyle]="{'background-image': 'url(' + backgroundImageURL + ')',
'background-size': backgroundSize, 'background-repeat': backgroundRepeat,
'background-position': 'center center'}">
</mat-sidenav-content>
其中 backgroundImageURL
、backgroundSize
和 backgroundRepeat
是我在 "environment.ts" 文件中定义的变量,
如何保存 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 内置的。
你应该这样做 ts
文件。
喜欢
let image = 'myImage';
if (window.innerWidth < 420) {
image += '-small';
} else if (window.innerWidth < 768) {
image += '-medium';
} else {
image += '-large';
}
this.backgroundImageURL = image;
从我的 .html 文件中的类似内容开始:
<mat-sidenav-content
[ngStyle]="{'background-image': 'url(' + backgroundImageURL + ')',
'background-size': backgroundSize, 'background-repeat': backgroundRepeat,
'background-position': 'center center'}">
</mat-sidenav-content>
其中 backgroundImageURL
、backgroundSize
和 backgroundRepeat
是我在 "environment.ts" 文件中定义的变量,
如何保存 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 内置的。
你应该这样做 ts
文件。
喜欢
let image = 'myImage';
if (window.innerWidth < 420) {
image += '-small';
} else if (window.innerWidth < 768) {
image += '-medium';
} else {
image += '-large';
}
this.backgroundImageURL = image;