如何为垫卡设置模糊背景图像

How set blurred background image for 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 变量设置初始背景图像,然后动态更改其 URL。

But this method does not suit me because pseudo elements are not part of DOM tree, and because of that do not expose any DOM API that can be used to interact with them

-是的,我们不能修改伪元素,因为它们不是 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变量