2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【jQuery】Google画像検索のような動きをプラグインなしで簡単実装

2
Last updated at Posted at 2019-08-01

やりたいこと

Google画像検索のように、画像をクリックすると詳細が下にアコーディオンで出てくる動き。

プラグインなしの方法を検索してみると、多くの変数を屈指して細かい動きを指定した実装が多かったのですが、
極力シンプルで簡潔な方法で実装してみます。
スクリーンショット 2019-08-01 18.44.18.png

HTML

<div class="wrap">

  <div class="itemThumbnail">image 1</div>
  <div class="itemDetail">
    <div class="itemDetail__inner">
      <div class="itemDetail__img">image 1</div>
      <div class="itemDetail__text">テキストテキストテキストテキストテキストテキストテキストテキストテキストテキスト</div>
      <div class="itemDetail__close"><img src="img/close.png" alt="クローズボタン"></div>
    </div>
  </div>

</div>

.itemThumbnail要素:横並びで表示され、クリックされる部分。
.itemDetail要素:クリックで下にアコーディオンで表示される部分。

.itemThumbnail.itemDetailでワンセット。表示したい分だけ繰り返す。

CSS

Google画像検索のような動きを実装するのに、必須なCSSだけ紹介します。

ポイント1:横並び要素にはinline-blockを使う

.itemThumbnail {
  display: inline-block;
}

display:inline-blockにすることで、詳細部分を展開しても、サムネイル要素をつめて表示してくれます。
代わりにfloat:leftにしてしまうと、詳細部分を展開した時、サムネイル要素を詰めて表示してくれません。
要素の横並びといえばdisplay:flexが便利ですが、今回の場合思い通りの動きになってくれません。

ポイント2:展開要素にはfloat:leftを使う

.itemThumbnail {
  float: left;
}

ポイント3:展開したら画面幅いっぱいに広げる

.itemThumbnail {
  position: relative;
  width: 100vw;
  left: 50%;
  transform: translateX(-50%);
}

なくても良いですが、よりそれっぽく仕上がります。

jQuery

展開の動きは、最低限のjQueryで。

$(function() {
  //サムネイル画像がクリックされたら
  $('.itemThumbnail').on('click',function(){
      // 1)全部非表示
      $('.itemDetail').hide();
      // 2)何番目か取得して表示
      var index = $('.itemThumbnail').index(this);
      $('.itemDetail').eq(index).slideToggle();
   });
  // ×ボタンがクリックされたら
  $('.itemDetail__close').on('click',function(){
    $('.itemDetail').slideUp();
  });
});

1)、2)は、サムネイル画像がクリックされてからの一連の動作です。
それでは上のコードを解説していきます。

1) 全部非表示

サムネイルがクリックされた時、まず始めに展開している詳細を全て閉じる必要があります
そうしないと、クリックする度にどんどん展開が起きてレイアウトが崩れてしまいます。
もしくは、いちいちバツボタンを押して閉じないといけない面倒な仕様になってしまいます。

2) 何番目か取得して表示

.itemThumbnail.itemDetailは同じページ内に複数存在しています。
何番目の.itemThumbnailがクリックされ、何番目の.itemDetailが展開するのかを指定することで、任意の箇所だけが開閉します。

おわりに

ホンモノのGoogle画像検索は、詳細を展開すると左右矢印が付いていて、矢印のクリックで詳細表示を切り替えられるようになっています。
今回はそこまで実装しませんでしたが、時間があるときに挑戦してみようと思います。

2
3
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
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?