JSFiddle - React, Tailwind, and code Playground
HTML
<div class="image-container">
<img src="https://picsum.photos/id/21/200/300" class="image image-top">
<img src="https://picsum.photos/id/22/200/300" class="image image-bottom">
</div>
CSS
.image-container {
position: relative;
width: 200px;
height: 300px;
overflow: hidden;
}
.image {
position: absolute;
inset: 0;
object-fit: cover;
transition: opacity 0.5s ease-in-out; /* 徐々に変化 */
}
.image-top {
z-index: 2;
opacity: 1;
}
.image-bottom {
z-index: 1;
}
JavaScript
const imageContainer = document.querySelector('.image-container');
const topImage = document.querySelector('.image-top');
imageContainer.addEventListener('mouseover', () => {
topImage.style.opacity = 0; // 上の画像を非表示
});
imageContainer.addEventListener('mouseout', () => {
topImage.style.opacity = 1; // 上の画像を再表示
});