Create a simple image carousel with navigation buttons
HTML
<div class="carousel">
<div class="slides">
<img src="https://images.unsplash.com/photo-1744614053463-491122164435?q=80&w=2070&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" alt="">
<img src="https://plus.unsplash.com/premium_photo-1744851723171-cfe67139e742?q=80&w=2071&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" alt="">
<img src="https://images.unsplash.com/photo-1743710426934-89887ca897d8?q=80&w=2138&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" alt="">
<img src="https://images.unsplash.com/photo-1726056652663-8f1e42b2fc95?q=80&w=2070&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDF8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" alt="">
<img src="https://plus.unsplash.com/premium_photo-1744967143306-0ec5b49ca2eb?q=80&w=2070&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" alt="">
</div>
<button class="prev">←</button>
<button class="next">→</button>
</div>
CSS
body {
display: flex;
justify-content: center; /* 水平置中 */
align-items: center; /* 垂直置中 */
height: 100vh; /* 設定高度為 100% 視窗高度 */
margin: 0; /* 移除預設 margin */
}
.carousel {
width: 300px;
overflow: hidden;
position: relative;
}
.slides {
display: flex;
transition: 0.2s opacity ease-in-out;
transition-delay: 0.2s;
}
.slides img {
width: 300px;
flex-shrink: 0;
}
.slides {
display: flex;
}
.prev, .next {
position: absolute;
top: 50%;
transform: translateY(-50%);
background-color: rgba(0, 0, 0, 0.5); /* 半透明背景 */
color: white;
padding: 10px;
border: none;
cursor: pointer;
font-size: 20px;
border-radius: 50%; /* 圓形按鈕 */
z-index: 10; /* 確保按鈕位於圖片的前面 */
transition: background-color 0.3s ease; /* 按鈕背景色過渡效果 */
}
/* 左側按鈕 */
.prev {
left: 10px;
}
/* 右側按鈕 */
.next {
right: 10px;
}
/* 懸停時改變背景顏色 */
.prev:hover, .next:hover {
background-color: rgba(0, 0, 0, 0.8); /* 懸停時背景顏色變深 */
}
JavaScript
let current = 0;
let length = document.querySelectorAll('.slides img').length;
const slides = document.querySelector('.slides');
document.querySelector('.next').addEventListener('click' , () =>{
current ++;
if ( current >= length ) {
current = 0
}
slides.style.transform = `translateX(-${300 * current}px)`;
})
document.querySelector('.prev').addEventListener('click' , ()=>{
current --;
if ( current < 0) {
current = length - 1;
}
slides.style.transform = `translateX(-${300 * current}px)`;
})