起初嘗試以Bootstrap的Carousel元件實作首頁倉鼠的照片幻燈片
後來想想,簡單的fade-in fade-out相片切換功能可以自己試著寫寫看
(自動輪播、無滑鼠鍵盤換頁功能)
設計方式很簡單
需先決定照片總張數,這裡我選擇四張,這會影響animation %數的計算及動畫總時長
現階段照片暫取自Unsplash
HTML
<div id="hamsterCarousel">
<div class="carousel-img"></div>
<div class="carousel-img"></div>
<div class="carousel-img"></div>
<div class="carousel-img"></div>
</div>
CSS
.carousel-img {
background-size: cover;
background-position: center center;
overflow: hidden;
//align-items、justify-content為使Welcome的String能置中
align-items: center;
justify-content: center;
position: absolute;
top: 3.5rem; //扣掉header高
left: 0;
width: 100%; //要設,不然會等於0、看不到圖
height: calc(100vh - 3.5rem);
visibility: hidden; //初始狀態都是隱藏
opacity: 0;
animation: slider 44s linear infinite;
//不是45秒,因為要無限循環,最後div(4)的淡出那一秒,div(1)便要開始了
}
//淡入淡出均1s,照片顯示時長為10s
#hamsterCarousel > div:nth-child(1) {
background-image: url("../assets/img/hamster01.jpg");
animation-delay: 0s;
}
#hamsterCarousel > div:nth-child(2) {
background-image: url("../assets/img/hamster02.jpg");
animation-delay: 11s;
}
#hamsterCarousel > div:nth-child(3) {
background-image: url("../assets/img/hamster03.jpg");
animation-delay: 22s;
}
#hamsterCarousel > div:nth-child(4) {
background-image: url("../assets/img/hamster04.jpg");
animation-delay: 33s;
}
//%數透過 x秒除以44秒而得,須精算
@keyframes slider {
0% {
visibility: hidden;
opacity: 0;
}
2.272727% {
visibility: visible;
opacity: 1;
}
25% {
visibility: visible;
opacity: 1;
}
27.272727%,
100% {
visibility: hidden;
opacity: 0;
}
}
完成!👏👏👏