要在五个不同的图像上设置相同的动画,但一次只显示一个图像的动画,同时确保其他图像回到原来的位置,可以使用CSS动画和JavaScript来控制动画的播放。以下是一个详细的解决方案:
@keyframes
定义动画序列。<div class="image-container">
<img src="image1.jpg" class="animated-image" data-index="0">
<img src="image2.jpg" class="animated-image" data-index="1">
<img src="image3.jpg" class="animated-image" data-index="2">
<img src="image4.jpg" class="animated-image" data-index="3">
<img src="image5.jpg" class="animated-image" data-index="4">
</div>
.image-container {
position: relative;
width: 500px;
height: 300px;
}
.animated-image {
position: absolute;
width: 100%;
height: 100%;
opacity: 0;
transition: opacity 0.5s ease-in-out;
}
.animated-image.active {
opacity: 1;
animation: fadeInOut 2s ease-in-out infinite;
}
@keyframes fadeInOut {
0%, 100% { transform: translateY(0); }
50% { transform: translateY(-20px); }
}
const images = document.querySelectorAll('.animated-image');
let currentIndex = 0;
function showNextImage() {
// Hide all images
images.forEach(img => img.classList.remove('active'));
// Show the next image
images[currentIndex].classList.add('active');
// Update the current index
currentIndex = (currentIndex + 1) % images.length;
}
// Start the animation loop
setInterval(showNextImage, 2000);
animated-image
和一个data-index
属性用于标识顺序。.image-container
:设置容器大小和相对定位。.animated-image
:初始状态下所有图像透明度为0,并设置过渡效果。.active
类:当图像激活时,设置透明度为1并应用动画效果。@keyframes fadeInOut
:定义图像的上下浮动动画。showNextImage
函数:隐藏所有图像,显示当前索引的图像,并更新索引。setInterval
:每2秒调用一次showNextImage
函数,实现轮流播放动画。通过这种方式,可以确保每次只有一个图像显示动画,其他图像回到原来的位置。
领取专属 10元无门槛券
手把手带您无忧上云