提问者:小点点

改变背景与url的角度


日安,

我正在尝试在单击按钮后更改我的背景url。 默认情况下,我的CSS上有这种样式。

.whole-container {
    background: linear-gradient(
                               rgba(0, 0, 0, 2.5),
                               rgba(0, 0, 0, 2.5)
    ), url('link-with-random-image') no-repeat center center fixed;

我的示例HTML如下所示:

<div class="whole-container">
    ....
</div>

我的问题是,我想在不重新加载页面的情况下触发背景的改变。

到目前为止,我所做的是这样的:

app.component.html

<div class="whole-container" [ngStyle]="{'background': wholeContainerStyle}">
    ...
</div>

app.component.ts

changeBg(){
    this.wholeContainerStyle = "linear-gradient(rgba(0, 0, 0, 2.5),rgba(0, 0, 0, 2.5)),url('link-with-random-image') no-repeat center center fixed;"
}

但背景图像没有改变。

有人帮忙吗?


共1个答案

匿名用户

如果需要在两种不同的样式之间切换,可以使用NGCLASS指令。

CSS

.whole-container-1 {
  background: 
    linear-gradient(rgba(0, 0, 0, 2.5), rgba(0, 0, 0, 2.5)), 
    url('link-with-random-image') no-repeat center center fixed;
}

.whole-container-2 {
  background: 
    linear-gradient(rgba(0, 0, 0, 2.5), rgba(0, 0, 0, 2.5)), 
    url('other-link-with-random-image') no-repeat center center fixed;
}

控制器

export class AppComponent {
  defaultStyle = true;
  ...
}

模板

<div [ngClass]="defaultStyle ? 'whole-container-1' : 'whole-container-2'">
    ...
</div>

<button (mouseup)="defaultStyle = !defaultStyle>Toggle style</button>