CSS 图片轮播是一种使用 CSS 动画和过渡效果来实现图片自动或手动切换的网页设计技术。它不需要复杂的 JavaScript 或服务器端逻辑,主要依赖于 CSS 的 animation
和 transition
属性。
以下是一个简单的 CSS 图片轮播示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Image Carousel</title>
<style>
.carousel {
width: 80%;
margin: 0 auto;
overflow: hidden;
position: relative;
}
.carousel img {
width: 100%;
display: none;
}
.carousel img:first-child {
display: block;
}
.carousel .active {
animation: carouselAnimation 5s infinite;
}
@keyframes carouselAnimation {
0% { opacity: 1; }
16.66% { opacity: 1; }
25% { opacity: 0; }
100% { opacity: 0; }
}
.carousel button {
position: absolute;
top: 50%;
transform: translateY(-50%);
}
.carousel button.prev {
left: 10px;
}
.carousel button.next {
right: 10px;
}
</style>
</head>
<body>
<div class="carousel">
<img src="image1.jpg" alt="Image 1">
<img src="image2.jpg" alt="Image 2">
<img src="image3.jpg" alt="Image 3">
<button class="prev">Prev</button>
<button class="next">Next</button>
</div>
<script>
const images = document.querySelectorAll('.carousel img');
let currentIndex = 0;
function showImage(index) {
images.forEach((img, i) => img.classList.remove('active'));
images[index].classList.add('active');
}
function nextImage() {
currentIndex = (currentIndex + 1) % images.length;
showImage(currentIndex);
}
function prevImage() {
currentIndex = (currentIndex - 1 + images.length) % images.length;
showImage(currentIndex);
}
document.querySelector('.next').addEventListener('click', nextImage);
document.querySelector('.prev').addEventListener('click', prevImage);
setInterval(nextImage, 5000);
</script>
</body>
</html>
will-change
属性优化动画性能:will-change: opacity;
通过以上方法和示例代码,你可以实现一个简单且高效的 CSS 图片轮播效果。
领取专属 10元无门槛券
手把手带您无忧上云