やりたいこと
画像のポップアップがしたい!
タグを設置
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();
});
スタイルを記載
スタイルシートに以下コードを追記します。
#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;
}
完成!

