0

我有带有动态背景图像的垫卡,我需要模糊此图像

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

我有什么: 示例我有 什么我需要什么: 示例我需要什么 这是我添加此代码后得到的:

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

4

1 回答 1

0

您可以通过 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 变量
于 2021-12-15T05:41:01.933 回答