js实现展示6个dom元素能自动轮播走马灯,并且能左右手动控制
时间: 2024-02-05 10:12:18 浏览: 95
可以使用JavaScript和CSS实现一个自动轮播的走马灯。下面是一个简单的示例代码:
HTML代码:
```html
<div class="carousel">
<div class="carousel-inner">
<div class="item active">
<img src="image1.jpg" alt="Image 1">
</div>
<div class="item">
<img src="image2.jpg" alt="Image 2">
</div>
<div class="item">
<img src="image3.jpg" alt="Image 3">
</div>
<div class="item">
<img src="image4.jpg" alt="Image 4">
</div>
<div class="item">
<img src="image5.jpg" alt="Image 5">
</div>
<div class="item">
<img src="image6.jpg" alt="Image 6">
</div>
</div>
<a class="left carousel-control" href="#myCarousel" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left"></span>
</a>
<a class="right carousel-control" href="#myCarousel" data-slide="next">
<span class="glyphicon glyphicon-chevron-right"></span>
</a>
</div>
```
CSS代码:
```css
.carousel-inner .item {
display: none;
}
.carousel-inner .active {
display: block;
}
.carousel-control {
display: none;
}
.carousel:hover .carousel-control {
display: block;
}
```
JavaScript代码:
```javascript
var slideIndex = 0;
var timer;
function showSlides() {
var i;
var slides = document.getElementsByClassName("item");
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
slideIndex++;
if (slideIndex > slides.length) {
slideIndex = 1;
}
slides[slideIndex - 1].style.display = "block";
timer = setTimeout(showSlides, 3000);
}
showSlides();
function plusSlides(n) {
clearTimeout(timer);
showSlides(slideIndex += n);
}
function currentSlide(n) {
clearTimeout(timer);
showSlides(slideIndex = n);
}
```
这个JavaScript代码会自动轮播图片,并且当鼠标悬停在轮播图上时,会显示左右箭头控制,可以手动控制轮播图。
阅读全文