安裝#
-
透過 npm
npm install animate.css --save
-
透過 yarn
yarn add animate.css
導入
import 'animate.css';
-
或者直接引入 css 檔案
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css"
/>
基本用法#
<h1 class="animate__animated animate__bounce">一個動畫元素</h1>
結合 js 實現點擊觸發動畫#
<!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="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css"
/>
<title>Document</title>
</head>
<body>
<div style="width: 100%; display: flex; justify-content: center">
<h1 id="animated">一個動畫元素</h1>
</div>
</body>
<script>
const animateCSS = (element, animation, prefix = "animate__") => {
// 我們創建一個 Promise 並返回它
new Promise((resolve, reject) => {
const animationName = `${prefix}${animation}`;
const node = document.querySelector(element);
node.classList.add(`${prefix}animated`, animationName);
// 當動畫結束時,我們清除類別並解析 Promise
function handleAnimationEnd(event) {
event.stopPropagation();
node.classList.remove(`${prefix}animated`, animationName);
resolve("動畫結束");
}
node.addEventListener("animationend", handleAnimationEnd, {
once: true,
});
});
};
document.getElementById("animated").addEventListener("click", () => {
animateCSS("#animated", "bounce");
});
</script>
</html>