見出し画像

【jQuery】小さな画像(サムネイル)をクリックしてメインの大きな画像を切り替える方法

「サムネイルをクリックするとメイン画像が切り替わるやつを実装したい」
→サムネイルを固定しているものはたくさん見つかったが、サムネイルごとメイン画像と切り替えているものが少なかったので備忘録

Retinaも対応

コード

html

<div class="mainImage mainItem">
    <img srcset="Retina画像のパス" src="通常サイズの画像のパス" alt="">
</div>
<div class="thumbnails subItem">
    <img srcset="Retina画像のパス" src="通常サイズの画像のパス" alt="">
    <img srcset="Retina画像のパス" src="通常サイズの画像のパス" alt="">
    <img srcset="Retina画像のパス" src="通常サイズの画像のパス" alt="">
</div>

css

main section .mainImage {
 width: 500px;
 margin: 0 auto;
}

main section .thumbnails {
 display: -webkit-box;
 display: -ms-flexbox;
 display: flex;
 -webkit-box-pack: distribute;
 -ms-flex-pack: distribute;
 justify-content: space-around;
 -ms-flex-wrap: wrap;
 flex-wrap: wrap;
 margin: 30px auto 0;
}

main section .thumbnails img {
 width: 300px;
 cursor: pointer;
 transition: all .3s;
}

main section .thumbnails img:hover {
 opacity: 0.8;
 transition: all .3s;
}

@media screen and (max-width: 768px) {
 main section .mainImage {
   width: 90%;
 }
 main section .thumbnails {
   margin: 30px auto 0;
 }
 main section .thumbnails img {
   width: 30%;
   margin: 0 auto 10px;
 }
 main section .thumbnails img:hover {
   opacity: 1;
 }
}

JS

$(function(){
   $('.subItem img').click(function(){
       // サムネイルの取得
       let $thisImg = $(this).attr('src');
       let $this2xImg = $(this).attr('srcset');
       let $thisAlt = $(this).attr('alt');

       // メインイメージの取得
       let $mainImg = $(".mainItem img").attr('src');
       let $main2xImg = $(".mainItem img").attr('srcset');
       let $mainAlt = $(".mainItem img").attr('alt');

       // メインイメージを一度非表示にする(アニメーション付与のため)
       $('.mainItem img').hide();

       // メインイメージとサムネイルを切り替える
       $('.mainItem img').attr({srcset:$this2xImg,src:$thisImg,alt:$thisAlt}).fadeIn(500);
       $(this).attr({srcset:$main2xImg,src:$mainImg,alt:$mainAlt});
   });
});


これで実装完了
html、css、jsは適宜変更


この記事が気に入ったらサポートをしてみませんか?