WordPress)はてなブログから移行した画像をポップアップ表示するようにした。
はてなブログからWordPressへ画像を移行して記事内で画像が表示されるようになったが、この画像をクリックしてポップアップ画像を表示するようにした。
<a>タグ、<div>タグを使わずに、<img>タグだけで画像を、ポップアップする方法を利用した。
テーマフォルダ「\wp-content\themes\iconic-one\」の以下のファイルにそれぞれ追記。
ポップアップする対象の画像は、class名が「hatena-fotolife」のものだけ。
<p><img class="hatena-fotolife" ....></p>
≪custom.css≫
※ ポップアップ画像がWordPressのヘッダーに隠れないように調整。
※ ポップアップ画像には白枠と角丸も付けている。
#modal-container {
display: none;
position: fixed;
background: rgba(0, 0, 0, 0.6);
top: 0;
bottom: 0;
left: 0;
right: 0;
z-index: 99;
}
#modal-container > div {
display: flex;
height: 100vh;
justify-content: center;
align-items: center;
}
#modal-container > div > img {
max-width: calc(100vw - 50px);
max-height: calc(100vh - 100px);
margin-top: 30px;
padding: 12px;
background-color: #fff;
box-shadow: 0 3px 18px -4px rgba(0, 0, 0, 0.8);
border-radius: 10px;
}
p > img.hatena-fotolife {
cursor: pointer;
}
figure > img.hatena-fotolife {
cursor: pointer;
}
≪header.php≫
※ jQueryを使う。
<script src="https://code.jquery.com/jquery-3.6.0.min.js" crossorigin="anonymous"></script>
≪footer.php≫
※ 既に<a>タグで囲われている<img>タグは除くため、<p>タグと<figure>タグ直下だけを対象にしている。
<div id="modal-container"><div><img src=""></div></div>
<script>
const modal = $('#modal-container');
const img = modal.find('img');
$('p > img.hatena-fotolife').each(function(index) { // <p>直下の<img>だけ対象
$(this).click(function() {
img.attr('src', $(this).attr('src'));
modal.show();
})
});
$('figure > img.hatena-fotolife').each(function(index) { // <figure>直下の<img>だけ対象
$(this).click(function() {
img.attr('src', $(this).attr('src'));
modal.show();
})
});
modal.click(function() {
$(this).hide();
});
</script>





