我使用 HTML、CSS 和 JS 为我的页面创建了幻灯片。
代码如下:
<div class="slideshow">
<div class="image__container">
<img src="/static/images/indoor2.jpg" alt="Indoor">
</div>
<div class="image__container">
<img src="/static/images/indoor3.jpg" alt="Indoor">
</div>
<div class="image__container">
<img src="/static/images/indoor4.jpg" alt="Indoor">
</div>
</div>
.slideshow {
position: relative;
animation: fadeInFromLeft 1.5s ease;
}
.image__container img {
height: 80vh;
width: 100%;
border-radius: 10px;
box-shadow: 0 20px 30px rgba(0, 0, 0, 0.2);
}
let slideIndex = 0;
showSlides();
function showSlides() {
const slides = document.getElementsByClassName('image__container');
// Hide all images
for (let i = 0; i < slides.length; i++) {
slides[i].style.display = 'none';
}
// Show curr image
slideIndex++;
if (slideIndex > slides.length) {
slideIndex = 1;
}
slides[slideIndex - 1].style.display = 'block';
// Repeat after 2 sec (2000ms)
setTimeout(showSlides, 3000);
}
幻灯片效果完美,但我想添加一些过渡,例如淡入。
我试过这样:
.slideshow {
position: relative;
animation: fadeInFromLeft 1.5s ease;
}
.image__container img {
animation: fadeInSlideshow 1s ease-in-out;
height: 80vh;
width: 100%;
border-radius: 10px;
box-shadow: 0 20px 30px rgba(0, 0, 0, 0.2);
}
@keyframes fadeInSlideshow {
from {
opacity: 0.5;
}
to {
opacity: 1;
}
}
但是,即使它有效,图像之间的过渡也不是最好的。
在动画和过渡领域还不是很实用,我想知道是否有人可以给我一些如何继续的建议,以便了解将来如何解决这个“问题”。
我感谢任何可以帮助我的回复。
提前谢谢您。
let slideIndex = 0;
showSlides();
function showSlides() {
const slides = document.getElementsByClassName('image__container');
for (let i = 0; i < slides.length; i++) {
slides[i].querySelector('img').classList.remove('active');
}
// Show curr image
slideIndex++;
if (slideIndex > slides.length) {
slideIndex = 1;
}
slides[slideIndex - 1].querySelector('img').classList.add('active');
// Repeat after 3 sec (3000ms)
setTimeout(showSlides, 3000);
}
.slideshow {
position: relative;
animation: fadeInFromLeft 1.5s ease;
}
.image__container img {
height: 80vh;
width: 100%;
border-radius: 10px;
box-shadow: 0 20px 30px rgba(0, 0, 0, 0.2);
opacity: 0;
transition: opacity 1s ease-in-out;
}
.image__container img.active {
opacity: 1;
}
<div class="slideshow">
<div class="image__container">
<img src="https://avatars.githubusercontent.com/u/12371363?v=4" alt="Indoor">
</div>
<div class="image__container">
<img src="https://avatars.githubusercontent.com/u/1493671?v=4" alt="Indoor">
</div>
<div class="image__container">
<img src=https://avatars.githubusercontent.com/u/11975561?v=4" alt="Indoor">
</div>
</div>
如果有效,请尝试一下。 请在 HTML 中使用正确的图像 URL。我使用的是互联网资源。