気持ちいいリストの下線アニメーション
マウスを流していったときに、気持ちいい感じのリストの下線アニメーションです。JavaScript + CSSで作れます。
CSSのみでも似たようなものは作れますが、ホバーアウト時の挙動に違いがあります。
▼実際のサンプル
Custom Code Lab手順1:HTML構造
次のような<ul>タグの中に<li>タグがあるHTML構造を前提としています。<ul>タグには識別子としてunderlineListというidを振っています。
手順2:CSSの設定
以下のようなCSSを記述します。
#underlinelist li {
position: relative;
/* 位置や太さは適宜設定してください */
.underline {
position: absolute;
left: 0;
bottom: 15%;
display: inline-block;
width: 0;
height: 2px;
background-color: currentColor;
}
}.underlineが下線の要素へのスタイルになります。位置や太さなどは適宜設定してください。
手順3:JavaScriptの設定
以下のようなJavaScriptを記述します。
const underlinelist = document.querySelector("#underlinelist");
// リストアイテムの要素を取得
const items = underlinelist.querySelectorAll("li");
// イージング関数
const easeOutQuart = "cubic-bezier(0.25, 1, 0.5, 1)";
// リストアイテムにspanタグを挿入
items.forEach((item) => {
const span = document.createElement("span");
span.classList.add("underline");
item.insertAdjacentElement("beforeend", span);
});
// 下線の要素を取得
const underlines = document.querySelectorAll(".underline");
// 下線のキーフレームアニメーション
const enterAnimationKeyframes = [
{ width: 0, easing: easeOutQuart },
{ width: "100%" },
];
const leaveAnimationKeyframes = [
{ width: "100%", easing: easeOutQuart },
{ width: 0 },
];
const underlineAnimations = Array.from(underlines).map((underline) => {
// 入るアニメーション
const enterAnimation = underline.animate(enterAnimationKeyframes, {
duration: 500,
iterations: 1,
fill: "forwards",
});
// 出るアニメーション
const leaveAnimation = underline.animate(leaveAnimationKeyframes, {
duration: 750,
iterations: 1,
fill: "forwards",
});
// 入るアニメーションはキャンセル(初期状態)で、出るアニメーションは終了(最終状態)しておくことで読み込み時のアニメーションを防ぐ
enterAnimation.cancel();
leaveAnimation.finish();
return { enterAnimation, leaveAnimation };
});
// アイテムそれぞれにイベントを設定
items.forEach((item, index) => {
item.addEventListener("mouseenter", () => {
underlineAnimations[index].leaveAnimation.cancel();
underlineAnimations[index].enterAnimation.play();
});
item.addEventListener("mouseleave", () => {
underlineAnimations[index].enterAnimation.cancel();
underlineAnimations[index].leaveAnimation.play();
});
});JavaScriptで動的にunderlineというクラスを持った<span>タグを挿入しています。Studio側の設定をできるだけ簡素にしたかったので動的なHTML挿入を行っています。
細かい実装のポイントは本家にて解説しています。
余韻のある下線のあるリスト - Web Motion CatalogCSSだけでは難しい、ちょっと気持ちのいい下線アニメーションをためてしてみてください。