本記事では、簡単にサムネイル付きスライドショー的なものの作り方の実装を紹介していきます。
形式は、haml,scss,JavaScript(jQuery)となっています。ご注意ください。
ファイルを用意する
- index.html.haml(以下名前は適当)
- index.scss
- index.js
としておきます。
index.html.haml
.show__contents__item-mainImage
%img.owl-lazy{:src => "https://static.mercdn.net/item/detail/orig/photos/m57633610047_1.jpg?1558747626"}/
.show__contents__item-thumbnails
%img.is-higher-width{:src => "https://static.mercdn.net/item/detail/orig/photos/m57633610047_1.jpg?1558747626"}/
%img.is-higher-width{:src => "https://static.mercdn.net/item/detail/orig/photos/m57633610047_2.jpg?1558747626"}/
%img.is-higher-width{:src => "https://static.mercdn.net/item/detail/orig/photos/m57633610047_4.jpg?1558747626"}/
%img.is-higher-width{:src => "https://static.mercdn.net/item/detail/orig/photos/m57633610047_1.jpg?1558747626"}/
%img.is-higher-width{:src => "https://static.mercdn.net/item/detail/orig/photos/m57633610047_2.jpg?1558747626"}/
このように作っておきます。
構造としては、div(mainImage)の下に、img(class:owl-lazy)div(thumbnails)の下に、(class:is-higher-width)があります。
index.scss
scssは、省略します。大きさなどを指定するくらいで、特別指定することはないです。
index.js
$(function(){
$('img.is-higher-width').mouseover(function(){
var $thisImg = $(this).attr('src');
$('img.owl-lazy').attr({src:$thisImg});
});
});
以上のように書くと、サムネ写真にマウスが触れたときに、メイン画像が切り替わると思います。
js部分について、解説しておくと、
$('img.is-higher-width').mouseover(function(){
サムネ画像(img.is-higher-width)にマウスが乗ったとき、
var $thisImg = $(this).attr('src');
this=(img.is-higher-width)の要素のsrc要素をattrで取得し、$thisImgに代入
$('img.owl-lazy').attr({src:$thisImg});
(img.owl-lazy)メイン画像に、サムネ画像のsrc要素をattrで当てる
以上のようなロジックを組んでいます。
上記手法を使って実装しましたが、見た目とサーバーサイドの実装との兼ね合いの上、slick.jsを用いて、再実装しています。後日、あらためて記事にできればと思います。