使用js代码实现轮播图
时间: 2024-02-26 22:57:31 浏览: 74
好的,以下是使用 JavaScript 实现轮播图的基本代码:
HTML 结构:
```html
<div class="slider">
<div class="slides">
<img src="slide1.jpg">
<img src="slide2.jpg">
<img src="slide3.jpg">
</div>
</div>
```
CSS 样式:
```css
.slider {
width: 500px;
height: 300px;
overflow: hidden;
position: relative;
}
.slides {
display: flex;
width: 100%;
height: 100%;
}
.slides img {
width: 100%;
height: 100%;
object-fit: cover;
}
```
JavaScript 代码:
```js
const slider = document.querySelector('.slider');
const slides = slider.querySelector('.slides').children;
const slideCount = slides.length;
let currentIndex = 0;
function showSlide(index) {
if (index < 0) {
index = slideCount - 1;
} else if (index >= slideCount) {
index = 0;
}
for (let i = 0; i < slideCount; i++) {
slides[i].style.display = 'none';
}
slides[index].style.display = 'block';
currentIndex = index;
}
showSlide(currentIndex);
setInterval(() => {
showSlide(currentIndex + 1);
}, 3000);
```
这段代码中,我们首先获取了轮播图容器、轮播图子元素和轮播图子元素数量。然后定义 `showSlide` 函数来显示指定索引的轮播图,并将当前索引保存到 `currentIndex` 变量中。最后使用 `setInterval` 函数每隔3秒自动切换到下一张轮播图。
阅读全文