首页 > 解决方案 > 如何将图像放在两者中在离子

问题描述

我目前正在开发 Ionic 应用程序并坚持在 ion-header 和 ion-content 中实现图像。

这是我如何实现的屏幕截图。正如你从截图中看到的那样,离子头和离子内容内容被隐藏了,因为我将图像设置z-index为高数字;

在此处输入图像描述

谁能建议如何实现这一目标?谢谢。

标签: cssangularionic-frameworkionic5

解决方案


有一种更简单的方法可以做到这一点,它是使用组件中的fullscreen属性ion-contentdocs)。所以诀窍是让内容全屏,然后将标题的背景设置为透明,这样它就不会覆盖背景。

模板:

<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>

款式:

ion-toolbar {
  --ion-toolbar-background: transparent;
}

ion-content {
  --background: url('/assets/your_image.jpg') no-repeat center center / cover;
}

重要提示:目前存在一个问题,导致背景图像在某些特定场景下闪烁(Github 问题)。如果此问题影响您的应用,建议的解决方法是在组件中设置背景,而不是像这样使用 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>

款式:

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) {}
  }
}

推荐阅读