全屏
 <p>
      <button class="btn">
        Animate
      </button>
    </p>
    <div class="container">
      <div class="box">
        
      </div>
    </div>
/* Copyright 2018 Google LLC.
SPDX-License-Identifier: Apache-2.0 */

/* CSS files add styling rules to your content */

body {
  font-family: "Benton Sans", "Helvetica Neue", helvetica, arial, sans-serif;
  margin: 2em;
}

.container {
  border: 4px solid #777;
  height: 70vh;
  display: flex;
  align-items: center;
  justify-content: center;
}

.box {
  background-color: #165baa;
  color: #fff;
  width: 100px;
  height: 100px;
  
}

.animate {
  animation: opacity 2.5s both;
}

@keyframes opacity {
  0% {
    opacity: 1;
  }
  50% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}
let btn = document.querySelector(".btn");
let item = document.querySelector(".box");

btn.addEventListener('click', (e) => {
    item.classList.toggle('animate');
    item.addEventListener('animationend', animationEndCallback);
});

let animationEndCallback = (e) => {
    item.removeEventListener('animationend', animationEndCallback);
    item.classList.remove('animate');
}
返回