通过单击按钮重置由CSS创建的动画

时间:2018-11-10 23:13:50

标签: javascript html css animation transform

我正在尝试通过单击按钮重置已应用于元素的动画。这是我的代码,我该怎么做?我尝试了一些但是没成功。

css代码

.slide-in-left {
  -webkit-animation:slide-in-left .5s cubic-bezier(.25,.46,.45,.94) both;
  animation:slide-in-left .5s cubic-bezier(.25,.46,.45,.94) both
}

@-webkit-keyframes slide-in-left{
  0% {
    -webkit-transform:translateX(-1000px);
    transform:translateX(-1000px);
    opacity:0
  }
  100% {
    -webkit-transform:translateX(0);
    transform:translateX(0);
    opacity:1
  }
}

@keyframes slide-in-left {
  0% {
    -webkit-transform:translateX(-1000px);
    transform:translateX(-1000px);
    opacity:0
  }
  100% {
    -webkit-transform:translateX(0);
    transform:translateX(0);
    opacity:1
  }
}

html代码

<div class="slide-in-left" style="background-color: green" id="myDIV">
  <p>{{totalCash}}</p>
</div>
<button (click)="sumCash(cashInput.value); cashInput.value=''" >Add</button>

js代码

sumCash() {
  this.totalCash += parseInt(this.cash);
};

这是stackblitz链接: https://stackblitz.com/edit/angular-k5soac

2 个答案:

答案 0 :(得分:0)

你应该做

<button onclick="myFunction();">

JavaScript:

function myFunction() {
    //or any other selector like 'getElementBy'...
    var demo = document.querySelector('#myElement');
    demo.style.animation="none";
};

答案 1 :(得分:0)

我这样使用setInterval()解决了我的问题; 首先从元素中删除类,然后在延迟后添加相同的类。现在它将再次触发相同的类。

我的css代码;

.slide-in-left{
  -webkit-animation:slide-in-left .5s cubic-bezier(.25,.46,.45,.94) both;
  animation:slide-in-left .5s cubic-bezier(.25,.46,.45,.94) both;
  background-color: green;
}

@-webkit-keyframes slide-in-left{0%{-webkit-transform:translateX(-1000px);transform:translateX(-1000px);opacity:0}100%{-webkit-transform:translateX(0);transform:translateX(0);opacity:1}}@keyframes slide-in-left{0%{-webkit-transform:translateX(-1000px);transform:translateX(-1000px);opacity:0}100%{-webkit-transform:translateX(0);transform:translateX(0);opacity:1}}

html代码

<p>Cash</p><input #cashInput placeholder="Add cash" [(ngModel)]="cash">
<div class="slide-in-left" id="myDiv">
<p>{{totalCash}}</p>
</div>
<button (click)="sumCash(cashInput.value); cashInput.value=''" onclick="sumCash($event);">Add</button>

ts代码

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  public cash: string = "0";
  public totalCash: number = 0;

  sumCash() {
    this.totalCash += parseInt(this.cash);
    this.cash = "0";

    var divItem = document.getElementById("myDiv");
    divItem.classList.remove("slide-in-left");

    var interval = setInterval(
      function() {
        divItem.classList.add("slide-in-left");
      }, 1
    );
  };
}

stackblitz链接: https://stackblitz.com/edit/angular-k5soac