使用js完成一个轮播图之小圆点+标题+色块
时间: 2023-08-08 17:07:41 浏览: 143
利用js来实现轮播图
以下是一个使用 JavaScript 实现轮播图的示例代码,包括小圆点、标题和色块:
HTML 代码:
```html
<div class="slider">
<ul class="slides">
<li class="slide active">
<img src="slide1.jpg" alt="Slide 1" />
<div class="content">
<h2>Title 1</h2>
<p>Description 1</p>
</div>
</li>
<li class="slide">
<img src="slide2.jpg" alt="Slide 2" />
<div class="content">
<h2>Title 2</h2>
<p>Description 2</p>
</div>
</li>
<li class="slide">
<img src="slide3.jpg" alt="Slide 3" />
<div class="content">
<h2>Title 3</h2>
<p>Description 3</p>
</div>
</li>
</ul>
<div class="dots"></div>
</div>
```
CSS 代码:
```css
.slider {
position: relative;
}
.slides {
list-style: none;
margin: 0;
padding: 0;
}
.slide {
position: absolute;
top: 0;
left: 0;
opacity: 0;
transition: opacity 0.5s ease-in-out;
}
.slide.active {
opacity: 1;
}
.content {
position: absolute;
bottom: 0;
left: 0;
width: 100%;
padding: 10px;
background-color: rgba(0, 0, 0, 0.5);
color: #fff;
}
.content h2 {
margin: 0;
font-size: 24px;
}
.content p {
margin: 0;
font-size: 16px;
}
.dots {
position: absolute;
bottom: 10px;
left: 50%;
transform: translateX(-50%);
display: flex;
}
.dot {
width: 10px;
height: 10px;
margin: 0 5px;
border-radius: 50%;
background-color: #ccc;
cursor: pointer;
}
.dot.active {
background-color: #fff;
}
```
JavaScript 代码:
```js
const slides = document.querySelectorAll('.slide');
const dots = document.querySelector('.dots');
let currentSlide = 0;
let interval = setInterval(nextSlide, 5000);
function nextSlide() {
slides[currentSlide].classList.remove('active');
currentSlide = (currentSlide + 1) % slides.length;
slides[currentSlide].classList.add('active');
updateDots();
}
function updateDots() {
dots.innerHTML = '';
for (let i = 0; i < slides.length; i++) {
const dot = document.createElement('div');
dot.classList.add('dot');
if (i === currentSlide) {
dot.classList.add('active');
}
dot.addEventListener('click', () => {
slides[currentSlide].classList.remove('active');
currentSlide = i;
slides[currentSlide].classList.add('active');
updateDots();
clearInterval(interval);
interval = setInterval(nextSlide, 5000);
});
dots.appendChild(dot);
}
}
updateDots();
```
这段代码实现了一个自动轮播的效果,每 5 秒钟自动切换到下一张图片,并且在图片下方添加了小圆点和标题、色块等内容。当用户点击小圆点时,会切换到对应的图片,并且停止自动轮播,等待 5 秒钟后重新开始自动轮播。
阅读全文