0
0

自己紹介ページのフッターを編集ー2

Posted at

お疲れ様です。

前回自己紹介ページのフッターに貼っている画像を、アニメーションを使ってじわりと表示するようにし、今日はその画像が順々に表示されるようコードを書きなおそうと思っていたのですが、冷静に考えると

「このページが表示された瞬間に画像たちがじわっと表示されてるから、スクロールしてたどり着くころには全部表示されてるし、これって意味ないんじゃ…?」

ということに気が付きましたので、かなり前に使った監視の observe を使っていきます:sweat_smile:

const imgItem = document.querySelectorAll('.item');

// 監視対象が範囲に交差したら実行する
const showItem = (entries) => {
for(let i = 0; i < imgItem.length; i++){
  const keyframes = {
    // 定数keyframesで画像の透明度を指定する
    opacity: [0, 1],
  };

// 再生時間の指定
  const option = {
    duration: 800,
  // fill: 'forwards'はキーフレームの状態を保持するという意味
    fill: 'forwards',
  };
imgItem[i].animate(keyframes, option);
}

entries[0].target.animate(keyframes, option);
};
// 監視の設定
const itemObserver = new IntersectionObserver(showItem);
// 監視するように指示
itemObserver.observer(document.querySelector('.item'));

とりあえず、以前のコードが直前にありましたので、見ながらコードを書いてみましたところ、itemObserver~の部分にエラーが出ました…
1つは observer ではなく observe でした 笑

もう1つは、今回.item は複数あるため、それらすべての監視が必要なので、それ用にしなければならないということでしたが、今の私にはそこまでの考えには至らず…

見直したりして定数名間違いなどないか確認した後、やっぱりchatGPT先生に泣きつきました。

// .itemの配列要素を個別に取得
const imgItem = document.querySelectorAll('.item');

// 監視対象が範囲に交差したら実行する
const showItem = (entries) => {

entries.forEach(entry => {
  if(entry.isIntersecting) {
 
-// for(let i = 0; i < imgItem.length; i++){
  const keyframes = {
    // 定数keyframesで画像の透明度を指定する
    opacity: [0, 1],
  };

// 再生時間の指定
  const option = {
    duration: 800,
  // fill: 'forwards'はキーフレームの状態を保持するという意味
    fill: 'forwards',
  };
-// imgItem[i].animate(keyframes, option);
-// }

entry.target.animate(keyframes, option);
}
});
};
// 監視の設定
const itemObserver = new IntersectionObserver(showItem);
// 各itemに対して監視するようにする
imgItem.forEach(item => itemObserver.observe(item));

-// // 監視するように指示
-// itemObserver.observe(document.querySelector('.item'));

赤い部分は1つ前のコードから削除した部分です。
更新し、ちゃんと交差した時に画像が表示されていることを確認しましたがなるほど…
今回は.item が4つあるので、forEach で各itemを監視するため、繰り返す必要がありますよね…
正解を示されてから改めて考えると、確かにそうです。
GPT先生から修正点をまとめたご説明もありましたので、よくよく読んでおきます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0