html,css,js实现轮播图代码
时间: 2024-01-01 15:04:46 浏览: 27
HTML部分:
```html
<div class="carousel">
<div class="carousel-content">
<img src="image1.jpg" alt="">
<img src="image2.jpg" alt="">
<img src="image3.jpg" alt="">
<img src="image4.jpg" alt="">
</div>
<div class="carousel-indicators">
<span class="indicator active"></span>
<span class="indicator"></span>
<span class="indicator"></span>
<span class="indicator"></span>
</div>
<a class="carousel-control prev"></a>
<a class="carousel-control next"></a>
</div>
```
CSS部分:
```css
.carousel {
position: relative;
width: 100%;
overflow: hidden;
}
.carousel-content {
position: relative;
width: 400%;
left: 0;
transition: left 0.5s ease;
}
.carousel-content img {
width: 25%;
float: left;
}
.carousel-indicators {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
}
.indicator {
display: inline-block;
width: 12px;
height: 12px;
border-radius: 50%;
background-color: #ddd;
margin-right: 10px;
cursor: pointer;
}
.indicator.active {
background-color: #555;
}
.carousel-control {
position: absolute;
top: 50%;
transform: translateY(-50%);
width: 40px;
height: 40px;
background-color: rgba(0, 0, 0, 0.5);
border-radius: 50%;
cursor: pointer;
}
.prev {
left: 20px;
}
.next {
right: 20px;
}
```
JavaScript部分:
```javascript
var carousel = document.querySelector('.carousel');
var carouselContent = document.querySelector('.carousel-content');
var images = document.querySelectorAll('.carousel-content img');
var indicators = document.querySelectorAll('.indicator');
var prevButton = document.querySelector('.prev');
var nextButton = document.querySelector('.next');
var currentIndex = 0;
var timer;
function goToSlide(index) {
carouselContent.style.left = -index * 100 + '%';
indicators[currentIndex].classList.remove('active');
indicators[index].classList.add('active');
currentIndex = index;
}
function goToNextSlide() {
var newIndex = (currentIndex + 1) % images.length;
goToSlide(newIndex);
}
function startTimer() {
timer = setInterval(goToNextSlide, 3000);
}
function stopTimer() {
clearInterval(timer);
}
indicators.forEach(function(indicator, index) {
indicator.addEventListener('click', function() {
stopTimer();
goToSlide(index);
startTimer();
});
});
prevButton.addEventListener('click', function() {
stopTimer();
var newIndex = currentIndex - 1;
if (newIndex < 0) {
newIndex = images.length - 1;
}
goToSlide(newIndex);
startTimer();
});
nextButton.addEventListener('click', function() {
stopTimer();
goToNextSlide();
startTimer();
});
startTimer();
```