如何用js添加css3动画

笔记2023-12-2726 人已阅来源:网络

你可以使用JavaScript来添加CSS3动画,其中一种常见的方法是通过操作DOM元素的类名。下面是一个简单的示例,演示了如何使用JavaScript添加CSS3动画:

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="styles.css">
  <title>CSS3 Animation Example</title>
</head>
<body>
  <button id="animateButton">Animate Box</button>
  <div id="box" class="box"></div>
  <script src="script.js"></script>
</body>
</html>

CSS(styles.css):

.box {
  width: 100px;
  height: 100px;
  background-color: red;
  transition: transform 0.5s ease; /* 定义动画过渡效果 */
  transform: scale(1); /* 初始状态 */
  margin-top: 20px;
}

.box.animate {
  transform: scale(1.5); /* 动画后的状态 */
}

JavaScript(script.js):

const animateButton = document.getElementById('animateButton');
const box = document.getElementById('box');

animateButton.addEventListener('click', function() {
  box.classList.toggle('animate'); // 添加或移除动画类名
});

在这个示例中,当用户点击按钮时,JavaScript会监听点击事件,并通过classList.toggle方法来添加或移除animate类名。CSS中定义了.animate类名的样式,包括了CSS3动画效果。这样就实现了通过JavaScript来控制CSS3动画的效果。

当用户点击按钮时,盒子会以动画的方式放大。这个示例展示了如何使用JavaScript来动态控制CSS3动画,这种方法在实际开发中非常常见。