jQuery - マウスオーバーしたサムネイル画像をメイン画像に表示/切り替え
はじめに
先程、"jQuery - マウスオーバーしたサムネイル画像をメイン画像に表示/切り替え"という技術記事をQiitaに投稿しました。 qiita.com
この記事の中で一番の肝となる、jQueryの動作の流れをもう少し詳しくこちらの記事に書いていきます。
※コードの記述方法というよりも、動作のイメージを掴む目的の記事です。
実際の動作はこちら
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'); // ①
サムネ画像にマウスオーバー
// マウスオーバーの処理 $(".thumbs__lists__item__image").mouseover(function(e){ // ② let mainDataIndex = $(this).parent().attr('data-index') // ③
z-indexをコントロール
$(".main__lists__image").each(function(index){ // ⑦ if(index == mainDataIndex){ // ⑧ $(this).css('z-index', 99); } else { $(this).css('z-index', -1); }; });
マウスオーバーしたサムネ画像がメイン画像に表示された状態になる。
サムネイル画像の半透明処理も同じロジックでopacityの値を変えれば 選択されている画像がわかりやすくなります。
そして、こうなる
大切なこと
こうした細かい部分は、すぐにググってコピペしがちですが
自分の脳みそで考えて図で表現できるようになると、今後似たような場面で
実装がスムーズにできるようになると思う。