【问题标题】:How set blurred background image for mat-card如何为 mat-card 设置模糊的背景图像
【发布时间】:2021-12-15 13:41:01
【问题描述】:

我有一张带有动态背景图片的 mat-card,我需要模糊这张图片

<mat-card [ngStyle]='{backgroundImage: backgroundImage}'>
  <mat-card-title>My card</mat-card-title>
  <mat-card-content>Card Content</mat-card-content>
</mat-card>

我的 CSS

mat-card {
  background-repeat: no-repeat;
  background-position: 50% 0;
  background-size: 100% 100%;
  /* this blure all card */
  filter: blur(8px);
  -webkit-filter: blur(8px);
}

我有什么: example what i have 我需要的: example what i need 这是我添加此代码后得到的结果:

mat-card:before {
    content: ' ';
    display: block;
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    z-index: 0;
    opacity: 0.2;
    background-image: url('img url');
    background-repeat: no-repeat;
    background-position: 50% 0;
    background-size: 100% 100%;
    filter: blur(10px);
    -webkit-filter: blur(10px);
  }

但是这种方法不适合我,因为伪元素不是 DOM 树的一部分,因此不会暴露任何可用于与它们交互的 DOM API

【问题讨论】:

    标签: css angular angular-material background-image mat-card


    【解决方案1】:

    您可以通过 CSS 变量设置初始背景图片,然后动态更改其 URL。

    但是这种方法不适合我,因为伪元素不是 DOM 树的一部分,因此不会暴露任何可用于与它们交互的 DOM API

    -是的,我们不能修改伪元素,因为它们不是 DOM 树的一部分。 但是我们可以改变 CSS 变量,伪元素可以引用它们。

    一个简单的例子:

    在你的样式中设置一个 CSS 变量:

    :host {
      --myCssVar: url("https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__480.jpg");
    }
    

    在 ::before 中引用这个变量:

    mat-card::before {
      content: " ";
      display: block;
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      z-index: 0;
      opacity: 0.2;
      background-image: var(--myCssVar); //Use reference
      background-repeat: no-repeat;
      background-position: 50% 0;
      background-size: 100% 100%;
      filter: blur(10px);
      -webkit-filter: blur(10px);
    }
    

    HTML:

    <mat-card>
      <mat-card-title>My card</mat-card-title>
      <mat-card-content>Card Content</mat-card-content>
    </mat-card>
    

    现在,您可以访问此 CSS 变量并动态修改它(构造函数示例):

    constructor(private elementRef: ElementRef) {
        setTimeout(() => {
          let host = elementRef.nativeElement;
          console.log(getComputedStyle(host).getPropertyValue('--myCssVar')); //Prints initial value
          host.style.setProperty(
            '--myCssVar',
            "url('https://interactive-examples.mdn.mozilla.net/media/cc0-images/grapefruit-slice-332-332.jpg')"
          );
        }, 4000);
      }
    
    • 我们正在使用 ElementRef 依赖注入访问宿主元素。
    • 然后,我们获取 nativeElement 并访问其上设置的 CSS 变量
    • 最后,我们使用host.style.setProperty()修改宿主元素上的CSS变量

    【讨论】:

    • 感谢您的帮助
    • @NiNjA_CaT 如果它解决了你的问题,你能把它标记为其他人关注的答案
    猜你喜欢
    • 1970-01-01
    • 2020-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多