JavaScript 控制 CSS 动画主要通过以下几种方式:
CSS 动画是通过 CSS 规则定义的动画效果,而 JavaScript 可以用来动态地控制这些动画的播放、暂停、重置等。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CSS Animation Control</title>
<style>
.box {
width: 100px;
height: 100px;
background-color: red;
transition: transform 1s;
}
.animate {
transform: translateX(200px);
}
</style>
</head>
<body>
<div id="box" class="box"></div>
<button onclick="toggleAnimation()">Toggle Animation</button>
<script>
function toggleAnimation() {
var box = document.getElementById('box');
box.classList.toggle('animate');
}
</script>
</body>
</html><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Web Animations API</title>
<style>
.box {
width: 100px;
height: 100px;
background-color: blue;
}
</style>
</head>
<body>
<div id="box" class="box"></div>
<button onclick="startAnimation()">Start Animation</button>
<script>
function startAnimation() {
var box = document.getElementById('box');
box.animate([
{ transform: 'translateX(0)' },
{ transform: 'translateX(200px)' }
], {
duration: 1000,
iterations: Infinity
});
}
</script>
</body>
</html>原因:可能是由于 JavaScript 执行阻塞了主线程,或者动画的复杂度过高。 解决方法:
requestAnimationFrame 来优化动画的执行时机。原因:可能是由于 JavaScript 代码中的逻辑错误,或者 CSS 规则未正确应用。 解决方法:
通过上述方法,可以有效地使用 JavaScript 来控制 CSS 动画,实现丰富的交互效果。