CSS 左右箭頭輪播圖是一種常見的網頁設計元素,它可以讓網頁內容更具視覺沖擊力,吸引用戶的注意力。接下來我們將介紹如何使用 CSS 實現一個簡單的左右箭頭輪播圖。
/* HTML 代碼 *//* CSS 代碼 */ .slider-container { position: relative; width: 100%; overflow: hidden; } .slider-wrapper { display: flex; width: 400%; transition: all 0.5s ease; } .slider-item { flex: 1 0 25%; height: 200px; text-align: center; line-height: 200px; font-size: 72px; } .slider-prev, .slider-next { position: absolute; top: 50%; transform: translateY(-50%); width: 40px; height: 40px; font-size: 32px; text-align: center; line-height: 40px; background-color: #fff; border: 1px solid #ccc; border-radius: 50%; cursor: pointer; } .slider-prev:hover, .slider-next:hover { background-color: #ccc; } .slider-prev { left: 20px; } .slider-next { right: 20px; } .slider-prev.disabled, .slider-next.disabled { opacity: 0.5; cursor: default; } /* JS 代碼 */ var wrapper = document.querySelector('.slider-wrapper'); var prevBtn = document.querySelector('.slider-prev'); var nextBtn = document.querySelector('.slider-next'); var currentIndex = 0; var totalSlides = 4; prevBtn.addEventListener('click', function() { if (currentIndex === 0) { return; } currentIndex--; wrapper.style.transform = 'translateX(-' + (currentIndex * 25) + '%)'; updateButtons(); }); nextBtn.addEventListener('click', function() { if (currentIndex === totalSlides - 1) { return; } currentIndex++; wrapper.style.transform = 'translateX(-' + (currentIndex * 25) + '%)'; updateButtons(); }); function updateButtons() { if (currentIndex === 0) { prevBtn.classList.add('disabled'); } else { prevBtn.classList.remove('disabled'); } if (currentIndex === totalSlides - 1) { nextBtn.classList.add('disabled'); } else { nextBtn.classList.remove('disabled'); } }
以上就是一個簡單的 CSS 左右箭頭輪播圖的實現示例,通過 flex 布局實現輪播圖的排列,通過 translateX 屬性實現輪播圖的滾動效果,通過 JavaScript 監聽箭頭按鈕的點擊事件并實現相應的滾動效果和按鈕樣式更新。