css基础之实现轮播图
要实现一个基本的轮播图,你可以使用以下的HTML和CSS代码。这里使用了简单的setInterval
函数来控制图片的切换。
HTML:
<div class="carousel">
<div class="carousel-inner">
<img class="active" src="image1.jpg" alt="Image 1">
<img src="image2.jpg" alt="Image 2">
<img src="image3.jpg" alt="Image 3">
</div>
<button class="carousel-control-prev">Previous</button>
<button class="carousel-control-next">Next</button>
</div>
CSS:
.carousel {
position: relative;
width: 300px;
height: 200px;
overflow: hidden;
}
.carousel-inner {
width: 300%;
height: 200px;
display: flex;
animation: slide 9s infinite;
}
.carousel-inner img {
width: 33.333%;
height: 200px;
opacity: 0;
transition: opacity 0.5s;
}
.carousel-inner img.active {
opacity: 1;
}
@keyframes slide {
0% { transform: translateX(0); }
11.1%, 33.3% { transform: translateX(0); }
44.4%, 66.6% { transform: translateX(-33.333%); }
77.7%, 100% { transform: translateX(-66.666%); }
}
.carousel-control-prev, .carousel-control-next {
position: absolute;
top: 50%;
transform: translateY(-50%);
font-size: 20px;
padding: 10px;
cursor: pointer;
}
.carousel-control-prev {
left: 10px;
}
.carousel-control-next {
right: 10px;
}
JavaScript:
document.addEventListener('DOMContentLoaded', function() {
var carousel = document.querySelector('.carousel');
var images = document.querySelectorAll('.carousel-inner img');
var currentIndex = 0;
function changeImage(direction) {
images[currentIndex].classList.remove('active');
currentIndex = (currentIndex + direction + images.length) % images.length;
images[currentIndex].classList.add('active');
}
setInterval(function() {
changeImage(1);
}, 3000);
carousel.querySelector('.carousel-control-prev').addEventListener('click', function() {
changeImage(-1);
});
carousel.querySelector('.carousel-control-next').addEventListener('click', function() {
changeImage(1);
});
});
这段代码实现了一个基本的自动轮播图,你可以根据需要添加更多的功能,比如手势支持、键盘导航、停止动画等。
评论已关闭