LoginSignup
5
5

More than 1 year has passed since last update.

画像をクリックするとポップアップで拡大するサンプル

Posted at

画像をクリックするとポップアップで拡大表示する、というのは良くありますが、プラグインなど追加せず書く必要に迫られたので対応しました。
せっかくなのでコードを共有します。

実装

HTML

対象のimgタグに、class="popup"を追加します。

HTML
<img src="qiita.png" class="popup">

拡大表示用のモーダル枠を確保します。表示されないので、どこでも良いです。

HTML
<div id="modal-container">
  <div><img src=""></div>
</div>

CSS

SCSS記法なので、CSSでは読み替えて下さい。

SCSS
#modal-container {
  display: none;
  position: fixed;
  background: rgba(0, 0, 0, .6);
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 99;
  & > div {
    display: flex;
    height: 100vh;
    justify-content: center;
    align-items: center;
    & > img {
      max-width: calc(100vw - 30px);
      max-height: calc(100vh - 30px);
    }
  }
}
img.popup {
  cursor: pointer;
}

JavaScript (ES2015)

要jQuery。

JS
const modal = $('#modal-container');
const img = modal.find('img');

$('img.popup').each(function(index) {
  $(this).click(function() {
    img.attr('src', $(this).attr('src'));
    modal.show();
  })
});

modal.click(function() {
  $(this).hide();
});

jQueryを使わない環境なら、

const modal = document.getElementById('modal-container');
images = document.querySelectorAll('img.popup');
modal.addEventListener('click', function() {
  modal.style.display = 'none';
}, false);

のような感じになるかと。

デモンストレーション

See the Pen Image popup sample by マインドウッド|ソフトウェアの修理屋さん (@mindwood) on CodePen.

5
5
2

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
5
5