实现轮播图完整代码
时间: 2023-09-22 13:07:50 浏览: 90
好的,以下是一个基于 jQuery 和 CSS3 实现的简单轮播图完整代码:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>轮播图</title>
<style>
.slider {
position: relative;
overflow: hidden;
width: 600px;
height: 400px;
}
.slider img {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: 0;
transition: opacity 1s ease-in-out;
}
.slider img.active {
opacity: 1;
}
.slider-nav {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
z-index: 1;
}
.slider-nav button {
display: inline-block;
width: 16px;
height: 16px;
margin: 0 10px;
border-radius: 50%;
border: none;
background-color: #ccc;
cursor: pointer;
}
.slider-nav button.active {
background-color: #000;
}
</style>
</head>
<body>
<div class="slider">
<img src="img1.jpg" class="active">
<img src="img2.jpg">
<img src="img3.jpg">
</div>
<div class="slider-nav">
<button class="active"></button>
<button></button>
<button></button>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(function() {
var $slider = $('.slider');
var $slides = $slider.find('img');
var $nav = $('.slider-nav');
var $buttons = $nav.find('button');
var currentSlide = 0;
var slideInterval = setInterval(nextSlide, 5000);
function nextSlide() {
$slides.eq(currentSlide).removeClass('active');
$buttons.eq(currentSlide).removeClass('active');
currentSlide = (currentSlide + 1) % $slides.length;
$slides.eq(currentSlide).addClass('active');
$buttons.eq(currentSlide).addClass('active');
}
$buttons.on('click', function() {
clearInterval(slideInterval);
$slides.eq(currentSlide).removeClass('active');
$buttons.eq(currentSlide).removeClass('active');
currentSlide = $(this).index();
$slides.eq(currentSlide).addClass('active');
$buttons.eq(currentSlide).addClass('active');
slideInterval = setInterval(nextSlide, 5000);
});
});
</script>
</body>
</html>
```
这个轮播图包括三张图片和三个导航按钮,每隔 5 秒自动切换到下一张图片。点击导航按钮可以手动切换图片。具体实现方式可以看代码中的注释。
阅读全文