はじめに
以下をCocoonで実現します。
Cocoonのマーカーは通常background-colorによる装飾ですが、アニメーションさせるためには linear-gradientを使って背景を左から右へ伸ばす工夫が必要です。
この記事では、この方法について説明します。
完成イメージ
- ホワイトスネイク
生物の記憶とスタンド能力を、CDのような形状の「DISC」にして取り出す、能力を持つ。
- C-MOON
ホワイトスネイクと、緑色の赤ちゃんが融合してできたスタンド。半径約3km以内にある物体の重力の方向を、本体のプッチ神父を中心に、逆転させる能力を持つ。
実装手順
以下のコードをjavascript.jsに追加します。
jQuery(function ($) {
const allMarkers = $('[class^="marker-"]');
const speedPerPx = 0.002; // 1pxあたりのアニメーション時間(秒)
// 各要素の初期設定
allMarkers.each(function () {
const className = $(this).attr('class');
const isUnderline = className.startsWith('marker-under-');
// マーカーの場合のグラデーション設定
if (!isUnderline) {
const bgColor = $(this).css('background-color');
$(this).css('background', `linear-gradient(to right, ${bgColor} 0%, ${bgColor} 100%)`);
}
// アニメーション用の初期スタイルを設定
$(this).css({
'background-repeat': 'no-repeat',
'background-size': '0% 100%',
'transition-property': 'background-size',
'transition-timing-function': 'linear',
});
// 要素の幅に応じてアニメーション時間を調整
const elWidth = $(this).width();
const duration = elWidth * speedPerPx;
$(this).css('transition-duration', duration + 's');
});
// 要素の状態を監視
const observer = new IntersectionObserver((entries, observer) => {
// 監視している要素を1つずつ処理
entries.forEach(entry => {
// 要素が画面内に入った場合
if (entry.isIntersecting) {
const $el = $(entry.target);
$el.css('background-size', '100% 100%');
// 一度画面内に入った要素は監視対象から削除
observer.unobserve(entry.target);
}
});
}, { threshold: 0.5 });
// すべてのマーカー要素を監視対象に登録
allMarkers.each(function () {
observer.observe(this);
});
});
さいごに
今回紹介した方法を使えば、マーカーに動きを加えることができ、目を引く装飾が実現できます。
文章にアクセントを加えたいときや、重要な部分を強調したいときに活用してみてください。


