nakauの技術ブログ 〜プログラミングを学ぶ〜

Ruby/Ruby on Rails/Javascript/jQuery/GitHub/AWS/Windows/Windowsバッチファイル/Powershell

jQuery - マウスオーバーしたサムネイル画像をメイン画像に表示/切り替え

はじめに

先程、"jQuery - マウスオーバーしたサムネイル画像をメイン画像に表示/切り替え"という技術記事をQiitaに投稿しました。 qiita.com

この記事の中で一番の肝となる、jQueryの動作の流れをもう少し詳しくこちらの記事に書いていきます。
※コードの記述方法というよりも、動作のイメージを掴む目的の記事です。

実際の動作はこちら

f:id:nakau_tech:20200823003725g:plain

jQuery コード (Qiita記事より)

$(function(){
  // 最初の画像のみ半透明解除
  $(".thumbs__lists__item__image").first().css('opacity', '1'); // ①
  // マウスオーバーの処理
  $(".thumbs__lists__item__image").mouseover(function(e){       // ②
    let mainDataIndex = $(this).parent().attr('data-index')     // ③
    $(".thumbs__lists__item__image").each(function(){           // ④
      let subDataIndex = $(this).parent().attr('data-index');   // ⑤
      if (subDataIndex == mainDataIndex){                       // ⑥
        $(this).css('opacity', '1');
      } else {
        $(this).css('opacity', '0.5');
      };
    });
    $(".main__lists__image").each(function(index){              // ⑦
      if(index == mainDataIndex){                               // ⑧
        $(this).css('z-index', 99);
      } else {
        $(this).css('z-index', -1);
      };
    });
  });
});

HTML、CSSはQiita記事のほうに記載されていますのでご確認ください。

図で挙動を説明

ページ読み込み時

  // 最初の画像のみ半透明解除
  $(".thumbs__lists__item__image").first().css('opacity', '1'); // ①

f:id:nakau_tech:20200823001009p:plain

サムネ画像にマウスオーバー

 // マウスオーバーの処理
  $(".thumbs__lists__item__image").mouseover(function(e){       // ②
   let mainDataIndex = $(this).parent().attr('data-index')     // ③

f:id:nakau_tech:20200823001012p:plain

z-indexをコントロール

    $(".main__lists__image").each(function(index){              // ⑦
      if(index == mainDataIndex){                               // ⑧
        $(this).css('z-index', 99);
      } else {
        $(this).css('z-index', -1);
      };
    });

f:id:nakau_tech:20200823001016p:plain f:id:nakau_tech:20200823001030p:plain

マウスオーバーしたサムネ画像がメイン画像に表示された状態になる。

f:id:nakau_tech:20200823001034p:plain

サムネイル画像の半透明処理も同じロジックでopacityの値を変えれば 選択されている画像がわかりやすくなります。

そして、こうなる

f:id:nakau_tech:20200823003725g:plain

大切なこと

こうした細かい部分は、すぐにググってコピペしがちですが
自分の脳みそで考えて図で表現できるようになると、今後似たような場面で
実装がスムーズにできるようになると思う。