有一种更简单的方法可以做到这一点,那就是使用fullscreen
财产来自ion-content
成分 (docs https://ionicframework.com/docs/api/content#properties)。所以技巧是让内容全屏,然后将标题的背景设置为透明,这样它就不会覆盖背景。
模板:
<ion-header class="ion-no-border">
<ion-toolbar>
<ion-title>Home</ion-title>
</ion-toolbar>
</ion-header>
<ion-content class="ion-padding" fullscreen>
...
...
</ion-content>
Styles:
ion-toolbar {
--ion-toolbar-background: transparent;
}
ion-content {
--background: url('/assets/your_image.jpg') no-repeat center center / cover;
}
重要的:目前存在一个问题,导致背景图像在某些特定场景中闪烁(Github问题 https://github.com/ionic-team/ionic-framework/issues/17494)。如果此问题影响您的应用程序,建议的解决方法是在组件中设置背景,而不是使用 css,如下所示:
模板:
<ion-header class="ion-no-border">
<ion-toolbar>
<ion-title>Home</ion-title>
</ion-toolbar>
</ion-header>
<!-- The only change is the id added to the ion-content -->
<ion-content id="my-page-content" class="ion-padding" fullscreen>
...
...
</ion-content>
Styles:
ion-toolbar {
--ion-toolbar-background: transparent;
}
ion-content {
// Do not set the background here!
}
成分:
import { DomController } from '@ionic/angular';
// ...
@Component({...})
export class MyPage {
constructor(private domController: DomController) {}
// ...
ionViewWillEnter() {
this.initializeBackground();
}
// ...
private initializeBackground(): void {
try {
const content = document.querySelector('#my-page-content');
const innerScroll = content.shadowRoot.querySelector('.inner-scroll');
this.domController.write(() => {
innerScroll.setAttribute(
'style',
'background: url("/assets/img/your_image.jpg") no-repeat center center / cover',
);
});
} catch (e) {}
}
}