如何更改弹出窗口的颜色

问题描述 投票:0回答:1

我构建了一个自定义弹出窗口,当我单击按钮时该弹出窗口可见。当我单击文档上的其他位置时,弹出窗口应该关闭/不可见。 效果非常好。

现在我想更改此弹出窗口的样式属性。问题是我无法改变它。

下面的代码返回 HTML 对象为空,但如果我单击具有相同功能的另一个按钮,样式会发生变化。

这是我到目前为止的代码:

工具提示.component.ts

export class TooltipComponent implements OnInit {
  popup = false;

  // open popup
  openToolTip($event: {
    target: any; stopPropagation: () => void; 
  }) 
  {
    
    $event.stopPropagation();
    this.popup = !this.popup;
    
   testvariable = document.getElementByID("popupId");
   testvariable.style.backgroundcolor = "green"; //backgroundcolor just for testing

  }
}

  // close popup if clicked on document
  @HostListener('document:click', ['$event']) onDocumentClick(event: any) {
    this.popup = false;
  }
 
  constructor() { }

  ngOnInit(): void {
  }

}

HTML

<span class="info-icon" (click)="openToolTip($event)">
    <mat-icon>info_outline</mat-icon>
</span>

<div *ngIf="popup" id="popupId" class="popup" (click)="$event.stopPropagation()">

    <div class="text-box">

    </div>

    <!-- close-button -->
    <a class="close" (click)="popup = false">&times;</a>
    
</div>
html css angular typescript
1个回答
0
投票

问题来自于元素还不知道。你检查得太快了。有多种方法可以修复它:

  1. 等一下.

您可以使用超时功能:

timeout(function() {
   var testvariable = document.getElementByID("popupId");
   testvariable.style.backgroundcolor = "green";
}, 0);
  1. 使用
    ngStyle
    设置样式。

如果样式应该取决于值,你可以这样做:

<div [ngStyle]="{'background-color': something ? 'green' : 'red'}">

</div>
  1. 更改默认样式

这将更改所有弹出窗口的样式,而不需要 JS 操作:

.popup {
   background-color: green;
}
  1. 通过ID更改样式

如果您使用特定ID,您可以这样做:

#popupId {
   background-color: green;
}

所有方法都有优点和缺点,您应该选择适合您所寻找的方法。

© www.soinside.com 2019 - 2024. All rights reserved.