我想创建一个淡入/淡出轮播。一切正常,但图像立即出现而不是淡入
// JavaScript for the fade carousel
const slides = document.querySelectorAll('.carousel-slide');
let currentSlide = 0;
// Show the first slide initially
slides[currentSlide].style.display = 'block';
function nextSlide() {
slides[currentSlide].style.display = 'none';
currentSlide = (currentSlide + 1) % slides.length;
slides[currentSlide].style.display = 'block';
}
// Automatically switch slides every 3 seconds
setInterval(nextSlide, 3000);
.carousel-container {
position: relative;
max-width: 600px;
margin: auto;
overflow: hidden;
}
.carousel-slide {
display: none;
width: 100%;
height: 100%;
}
<div class="carousel-container">
<img class="carousel-slide" src="https://fakeimg.pl/600x200?text=Nurses" alt="Slide 1">
<img class="carousel-slide" src="https://fakeimg.pl/600x200?text=Barbers" alt="Slide 2">
<img class="carousel-slide" src="https://fakeimg.pl/600x200?text=Receptionist" alt="Slide 3">
</div>
只需使用不透明度和 CSS 过渡。如果您需要更多控制,您还可以监听
transitionend
事件。
// JavaScript for the fade carousel
const slides = document.querySelectorAll('.carousel-slide');
let currentSlide = 0;
// Show the first slide initially
slides[currentSlide].style.opacity = '1';
function nextSlide() {
slides[currentSlide].style.opacity = '0';
currentSlide = (currentSlide + 1) % slides.length;
slides[currentSlide].style.opacity = '1';
}
// Automatically switch slides every 3 seconds
setInterval(nextSlide, 3000);
.carousel-container {
position: relative;
max-width: 600px;
margin: auto;
overflow: hidden;
width: 100%;
aspect-ratio: 16/9;
}
.carousel-slide {
width: 100%;
height: 100%;
transition: opacity 1s ease-out;
opacity: 0;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
<div class="carousel-container">
<img class="carousel-slide" src="https://fakeimg.pl/600x400?text=Nurses" alt="Slide 1">
<img class="carousel-slide" src="https://fakeimg.pl/600x400?text=Barbers" alt="Slide 2">
<img class="carousel-slide" src="https://fakeimg.pl/600x400?text=Receptionist" alt="Slide 3">
</div>