写一个轮播图代码
时间: 2024-02-12 19:07:10 浏览: 74
好的,以下是一个基于jQuery的轮播图代码示例:
HTML代码:
```html
<div class="slider">
<div class="slider-wrapper">
<div class="slider-item active">
<img src="https://via.placeholder.com/500x300?text=Slide+1" alt="Slider 1">
</div>
<div class="slider-item">
<img src="https://via.placeholder.com/500x300?text=Slide+2" alt="Slider 2">
</div>
<div class="slider-item">
<img src="https://via.placeholder.com/500x300?text=Slide+3" alt="Slider 3">
</div>
</div>
<div class="slider-controls">
<span class="slider-control active"></span>
<span class="slider-control"></span>
<span class="slider-control"></span>
</div>
</div>
```
CSS代码:
```css
.slider {
position: relative;
width: 500px;
height: 300px;
overflow: hidden;
}
.slider-wrapper {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
}
.slider-item {
flex: 0 0 100%;
}
.slider-item img {
width: 100%;
height: 100%;
object-fit: cover;
}
.slider-controls {
position: absolute;
bottom: 10px;
right: 10px;
}
.slider-control {
display: inline-block;
width: 10px;
height: 10px;
border-radius: 50%;
background-color: #ccc;
margin-right: 10px;
cursor: pointer;
}
.slider-control.active {
background-color: #333;
}
```
JavaScript代码:
```js
$(document).ready(function() {
var slider = $('.slider');
var sliderWrapper = slider.find('.slider-wrapper');
var sliderItems = slider.find('.slider-item');
var sliderControls = slider.find('.slider-control');
var activeIndex = 0;
// 初始化轮播图
sliderItems.first().addClass('active');
sliderControls.first().addClass('active');
// 绑定轮播控制事件
sliderControls.click(function() {
var index = $(this).index();
activeIndex = index;
sliderItems.removeClass('active').eq(index).addClass('active');
sliderControls.removeClass('active').eq(index).addClass('active');
});
// 自动轮播
setInterval(function() {
activeIndex++;
if (activeIndex >= sliderItems.length) {
activeIndex = 0;
}
sliderItems.removeClass('active').eq(activeIndex).addClass('active');
sliderControls.removeClass('active').eq(activeIndex).addClass('active');
}, 3000);
});
```
以上代码实现了一个基本的轮播图效果,您可以根据自己的需求进行修改和优化。
阅读全文