サムネイルをクリックすると画像が切り替わる

目次

作りたいもの

サムネイルをクリックするとメイン画像が切り替わるようにしたい

See the Pen Untitled by Tomo56 (@tomokoro) on CodePen.

HTML

<div class="container">
    <div class="center">
        <div class="main-img">
            <img src="https://drive.google.com/uc?export=view&id=108Z-74dPI1eEKMh7FMEvwavNnJnnJDD5" id="main-img">
        </div>
        <ul class="thumb-items">
            <li class="thumb-item"><img src="https://drive.google.com/uc?export=view&id=108Z-74dPI1eEKMh7FMEvwavNnJnnJDD5" class="thumb" data-image="https://drive.google.com/uc?export=view&id=108Z-74dPI1eEKMh7FMEvwavNnJnnJDD5"></li>
            <li class="thumb-item"><img src="https://drive.google.com/uc?export=view&id=1IGCMa6e5_3cTebvwY6X-BetSYmQQNr4_" class="thumb" data-image="https://drive.google.com/uc?export=view&id=1IGCMa6e5_3cTebvwY6X-BetSYmQQNr4_"></li>
            <li class="thumb-item"><img src="https://drive.google.com/uc?export=view&id=1hnT8w0BARIFg2oKY8WGFRBVGtDFM63iJ" class="thumb" data-image="https://drive.google.com/uc?export=view&id=1hnT8w0BARIFg2oKY8WGFRBVGtDFM63iJ"></li>
            <li class="thumb-item"><img src="https://drive.google.com/uc?export=view&id=1u_ylDKHk2_goXwMHoEa4Nn3z0xPpQDTW" class="thumb" data-image="https://drive.google.com/uc?export=view&id=1u_ylDKHk2_goXwMHoEa4Nn3z0xPpQDTW"></li>
        </ul>
    </div>
</div>

CSS

img {
  aspect-ratio:4/3;
  width: 100%;
  height: 100%;
}

.center {
    max-width: 500px;
    width: 100%;
    margin: 50px auto 0 auto;
}

.thumb-items {
    display: flex;
    margin: 0;
    padding: 0;
    list-style-type: none;
}

.thumb-item {
    flex: 1 1 auto;
    margin-left: 6px;
}

.thumb-item:first-of-type {
    margin-left: 0;
}

JavaScript

const thumbs = document.querySelectorAll('.thumb');
thumbs.forEach(function(item, index) {
    item.onclick = function() {
        document.getElementById('main-img').src = this.dataset.image;
    }
});
よかったらシェアしてね!
  • URLをコピーしました!
目次