实现焦点轮播图的效果,有01.jpg,02.jpg,03.jpg三张图片,要求如下:1.当页面加载完成后,三张图片每2秒自动切换一张图片,2.切换图片时,其对应按钮的样式同步变换——背景颜色变成红色,3.当鼠标悬停在某个按钮上时,显示该按钮对应的图片且轮播停止,给出完整代码
时间: 2023-12-06 11:03:10 浏览: 63
HTML代码:
```
<div class="carousel">
<ul class="carousel-list">
<li class="carousel-item"><img src="01.jpg" alt=""></li>
<li class="carousel-item"><img src="02.jpg" alt=""></li>
<li class="carousel-item"><img src="03.jpg" alt=""></li>
</ul>
<div class="carousel-buttons">
<a href="#" class="carousel-button active"></a>
<a href="#" class="carousel-button"></a>
<a href="#" class="carousel-button"></a>
</div>
</div>
```
CSS代码:
```
.carousel {
position: relative;
width: 600px;
height: 400px;
margin: 0 auto;
}
.carousel-list {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
margin: 0;
padding: 0;
list-style: none;
overflow: hidden;
}
.carousel-item {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: 0;
transition: opacity 1s ease-in-out;
}
.carousel-item img {
width: 100%;
height: 100%;
}
.carousel-item.active {
opacity: 1;
}
.carousel-buttons {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
}
.carousel-button {
display: inline-block;
width: 10px;
height: 10px;
margin: 0 10px;
background-color: #ccc;
border-radius: 50%;
}
.carousel-button.active {
background-color: #f00;
}
```
JavaScript代码:
```
var carousel = document.querySelector('.carousel');
var carouselList = document.querySelector('.carousel-list');
var carouselItems = document.querySelectorAll('.carousel-item');
var carouselButtons = document.querySelectorAll('.carousel-button');
var currentIndex = 0;
var timer;
// 切换图片
function changeCarousel() {
carouselItems[currentIndex].classList.remove('active');
carouselButtons[currentIndex].classList.remove('active');
currentIndex = (currentIndex + 1) % carouselItems.length;
carouselItems[currentIndex].classList.add('active');
carouselButtons[currentIndex].classList.add('active');
}
// 自动轮播
timer = setInterval(changeCarousel, 2000);
// 点击按钮切换图片
carouselButtons.forEach(function(button, index) {
button.addEventListener('click', function(event) {
event.preventDefault();
clearInterval(timer);
carouselItems[currentIndex].classList.remove('active');
carouselButtons[currentIndex].classList.remove('active');
currentIndex = index;
carouselItems[currentIndex].classList.add('active');
carouselButtons[currentIndex].classList.add('active');
timer = setInterval(changeCarousel, 2000);
});
});
// 鼠标悬停停止自动轮播
carousel.addEventListener('mouseover', function() {
clearInterval(timer);
});
// 鼠标离开开始自动轮播
carousel.addEventListener('mouseout', function() {
timer = setInterval(changeCarousel, 2000);
});
```
阅读全文