写一个JavaScript轮播图代码
时间: 2024-03-24 08:41:51 浏览: 74
好的,下面是一个简单的JavaScript轮播图代码,你可以根据需要进行修改:
HTML:
```html
<div class="slideshow-container">
<div class="slide fade">
<img src="slide1.jpg">
</div>
<div class="slide fade">
<img src="slide2.jpg">
</div>
<div class="slide fade">
<img src="slide3.jpg">
</div>
</div>
<div class="dots-container">
<span class="dot"></span>
<span class="dot"></span>
<span class="dot"></span>
</div>
```
CSS:
```css
.slideshow-container {
max-width: 1000px;
position: relative;
margin: auto;
}
.fade {
-webkit-animation-name: fade;
-webkit-animation-duration: 1s;
animation-name: fade;
animation-duration: 1s;
}
@-webkit-keyframes fade {
from {
opacity: .4
}
to {
opacity: 1
}
}
@keyframes fade {
from {
opacity: .4
}
to {
opacity: 1
}
}
.dots-container {
text-align: center;
margin-top: 20px;
}
.dot {
height: 15px;
width: 15px;
margin: 0 5px;
border-radius: 50%;
display: inline-block;
background-color: #bbb;
}
.active {
background-color: #717171;
}
```
JavaScript:
```js
var slideIndex = 1;
showSlides(slideIndex);
// Next/previous controls
function plusSlides(n) {
showSlides(slideIndex += n);
}
// Thumbnail image controls
function currentSlide(n) {
showSlides(slideIndex = n);
}
function showSlides(n) {
var i;
var slides = document.getElementsByClassName("slide");
var dots = document.getElementsByClassName("dot");
if (n > slides.length) {slideIndex = 1}
if (n < 1) {slideIndex = slides.length}
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(" active", "");
}
slides[slideIndex-1].style.display = "block";
dots[slideIndex-1].className += " active";
}
```
这个代码创建了一个基本的轮播图,其中包含三张图片和三个圆点,用户可以点击圆点或箭头来切换图片。你可以根据需要进行修改,例如改变图片数量,调整样式等。
阅读全文