结合 CSS 动画使用
Anime.js 和 CSS 动画各有优劣。结合使用可以让动画既有良好性能,又方便管理和复用。
1. 何时使用 CSS 动画
- 简单的过渡和循环动画。
- 需要通过类名控制的状态切换。
- 利用浏览器优化,性能更佳。
2. 何时使用 Anime.js
- 复杂的序列动画和事件控制。
- 动态生成动画参数。
- 需要精确控制动画时序。
3. 结合使用示例
通过 Anime.js 触发 CSS 动画类切换,完成复杂效果。
<div class="box"></div>
<button id="startBtn">开始动画</button>
<style>
.box {
width: 100px;
height: 100px;
background: #4fc08d;
border-radius: 10px;
margin: 20px auto;
transition: transform 0.5s ease;
}
.rotate {
animation: rotate360 2s linear infinite;
}
@keyframes rotate360 {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
</style>
<script>
const box = document.querySelector(".box");
const btn = document.getElementById("startBtn");
btn.addEventListener("click", () => {
anime({
targets: box,
translateY: 100,
duration: 1000,
easing: "easeInOutQuad",
complete: () => {
box.classList.add("rotate");
},
});
});
</script>
4. 优势总结
- CSS 动画高效且易管理。
- Anime.js 适合动态控制和复杂时序。
- 结合使用更灵活,提升体验。
代码示例
源码
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<title>结合 CSS 动画使用示例</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
padding: 40px;
background: #fafafa;
}
.box {
width: 100px;
height: 100px;
background: #4fc08d;
border-radius: 10px;
margin: 20px auto;
}
.rotate {
animation: rotate360 2s linear infinite;
}
@keyframes rotate360 {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
button {
margin-top: 30px;
padding: 10px 24px;
font-size: 16px;
cursor: pointer;
border: none;
border-radius: 6px;
background-color: #4fc08d;
color: white;
transition: background-color 0.3s;
}
button:hover {
background-color: #3a9d6f;
}
</style>
</head>
<body>
<div class="box"></div>
<button id="startBtn">开始动画</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js"></script>
<script>
(function () {
const box = document.querySelector(‘.box’);
const btn = document.getElementById(‘startBtn’);
btn.addEventListener('click', () => {
anime({
targets: box,
translateY: 100,
duration: 1000,
easing: 'easeInOutQuad',
complete: () => {
box.classList.add('rotate');
}
});
});
})();
</script>
</body>
</html>
相关内容
- Anime.js 简介 本节介绍 Anime.js 是什么,它是一款轻量级、功能丰富的 JavaScript 动画库,适用于构建现代网页中的各种动效。通过 Anime.js,开发者可以...
- 引入方式 本节介绍如何将 Anime.js 应用到你的项目中,包括使用 CDN、NPM 安装以及与构建工具和框架集成的方法,帮助你根据项目需求选择最佳的引入方式。
- 目标元素 targets 本节介绍 Anime.js 中 targets 的使用方法,包括选择器、DOM 节点、NodeList、数组等不同形式的目标设置方式,并讲解如何同时对多个元素进...
- 常用属性动画 本节介绍 Anime.js 中最常用的动画属性,包括位移、缩放、旋转、透明度、颜色等,帮助开发者快速掌握实际动画制作中的常见属性及应用技巧。
- 基本参数设置 本节介绍 Anime.js 动画的基础参数配置,包括持续时间、延迟、缓动函数、循环、方向等,帮助开发者灵活控制动画表现。
- 事件监听 本节介绍 Anime.js 中动画事件监听机制,包括动画开始、更新、完成和停止等事件的使用方法,帮助开发者灵活响应动画状态变化。