【JavaScript】ホバーしたら、画像が切り替わるイメージギャラリー
2025年10月27日
WEBサイト制作
- #HTML
- #css
- #JavaScript
- #tips
こんにちは!
上毛印刷WEB制作担当のソーヤです。
今回は、以前の記事の変化版を紹介します!
◆過去記事はコチラ(【JavaScript】イメージギャラリー、クリックで画像切り替え)
実装したので、紹介します!
実装例
HTML例
<div class="gallery">
<div class="gallery-img">
<img src="/cp/wp/wp-content/uploads/2023/08/gallery_01.jpg" alt="" id="js-image-target">
</div>
<ul class="gallery-list">
<li class="gallery-list-item">
<button class="js-image"><img src="/cp/wp/wp-content/uploads/2025/08/gallery_01.jpg" alt=""></button>
</li>
<li class="gallery-list-item">
<button class="js-image"><img src="/cp/wp/wp-content/uploads/2025/08/gallery_02.jpg" alt=""></button>
</li>
<li class="gallery-list-item">
<button class="js-image"><img src="/cp/wp/wp-content/uploads/2025/08/gallery_03.jpg" alt=""></button>
</li>
<li class="gallery-list-item">
<button class="js-image"><img src="/cp/wp/wp-content/uploads/2025/08/gallery_04.jpg" alt=""></button>
</li>
</ul>
</div>CSS例
.gallery img{
width: 100%;
}
.gallery-img{
margin: auto;
max-width: 600px;
}
.gallery-list{
padding: 0;
list-style: none;
display: flex;
justify-content: center;
}
.js-image{
cursor: pointer;
border: none;
background: none;
transition: .4s;
}
.js-image:hover{
opacity: 0.4;
}JavaScript例
window.addEventListener('DOMContentLoaded', function(){
let imageBtn = document.getElementsByClassName('js-image');
let imageMain = document.getElementById('js-image-target');
for (let i = 0; i < imageBtn.length; i++) {
imageBtn[i].addEventListener('mouseenter', function(){
let imageStack = this.firstElementChild.getAttribute('src');
imageMain.setAttribute('src', imageStack);
}, false);
}
});まとめ
今回もjQueryではなく、Vanilla.jsで実装してみました。
コピペしてガンガン使ってください!
この記事に対するご意見・ご感想・ご質問等ありましたら、
ぜひ下記フォームにてお送りください。