HTML / CSS-几秒钟后使警报消失

时间:2018-07-25 19:33:51

标签: html css angular

我发出了警报,当按下按钮时会弹出通知用户已将文本复制到剪贴板

 <div class="alert alert-success" *ngIf="message?.length > 0" role="alert">{{ message }}</div>
 <button class="btn btn-default" (click)="copy(token)" role="button">Copy</button>

该按钮调用填充“消息”字符串的方法。

我正在尝试找到一种使用html或css的方法,以便在几秒钟后删除此元素。我尝试为其创建动画

.alert-success {
    -webkit-animation: cssAnimation 5s forwards; 
    animation: cssAnimation 5s forwards;
}

@keyframes cssAnimation {
    0%   {opacity: 1;}
    90%  {opacity: 1;}
    100% {opacity: 0;}
}

@-webkit-keyframes cssAnimation {
    0%   {opacity: 1;}
    90%  {opacity: 1;}
    100% {opacity: 0;}
}

这几乎可以解决问题,但是,它只是将元素设置为不可见。创建警报后,它将按钮和警报下方的所有元素向下移动,并且当警报“消失”时,它将在按钮应移回的位置留出较大的空白。

有没有办法做到这一点?

3 个答案:

答案 0 :(得分:2)

还要添加display: none

@-webkit-keyframes cssAnimation {
    0%   {opacity: 1;}
    90%  {opacity: 1;}
    100% {opacity: 0; display: none;}
}

动画结束后,使用JavaScript事件Detect the End of CSS Animations and Transitions with JavaScript — Jonathan Suh以编程方式使用.hide()函数正确隐藏元素。

类似的东西:

$(element).on("webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend", function () {
  $(this).hide();
});

答案 1 :(得分:0)

您可以使用[class.visible]="isVisible"来绑定CSS类的存在 和setTimeout的功能是在几秒钟后将isVisible切换为false。

模板

<button (click)="showAlert()">show alert</button>

<div class="alert" [class.visible]="isVisible"> 
  JWT copied to clipboard
</div>

组件

export class AppComponent  {

  public isVisible: boolean = false;

  showAlert() : void {
    if (this.isVisible) { // if the alert is visible return
      return;
    } 
    this.isVisible = true;
    setTimeout(()=> this.isVisible = false,2500); // hide the alert after 2.5s
  }

}

警报样式

.alert  {
  position: fixed;
  top: 0;
  right: 0.5rem;
  border:1px solid rgba(0, 0, 0, 0.2);
  border-radius: 0.25rem;
  padding: 2rem;
  background: #fff;
  color: #f65656;
  box-shadow: 0 5px 10px -5px rgba(0, 0, 0, 0.5);
  transition:  all 0.2s ease-in-out;
  opacity: 0;
}

.visible {
  opacity: 1;
  transform: translateY(1.25rem);
}

stackblitz example

答案 2 :(得分:0)

   // Success Message will disappear after 4 sec in angular7
   export class UnsubscribeComponent implements OnInit {
   hideSuccessMessage = false;

   FadeOutSuccessMsg() {
   setTimeout( () => {
       this.hideSuccessMessage = true;
    }, 4000);
}

 component.html -
 ------------------
      <div  *ngIf="!hideSuccessMessage">
        <div class="col-12">
          <p class="alert alert-success">
              <strong [ngClass] ="FadeOutSuccessMsg()" >You are successfully 
              unsubscribe from this email service.</strong>                 
          </p>
        </div>
      </div>