javascript

投稿日:

画像の拡大表示(ポップアップ)

タグを設置

html内であればどこでも良い。

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

画像にクラスを付与

<img src="~~" class="popup">

スクリプトを記載

jQuery 使用

const modal = jQuery('#modal-container');
    const img = modal.find('img');
    jQuery('img.popup').each(function(index) {
        jQuery(this).click(function() {
            img.attr('src', jQuery(this).attr('src'));
            modal.show();
        })
    });
    modal.click(function() {
        $(this).hide();
    });

スタイルを記載

任意の.cssに追記

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

- javascript

関連記事

関連記事はありませんでした