运用JavaScript制作图片的滚动和轮换,通过点击左右两侧的箭头可以实现焦点图按顺序切换,当鼠标滑动到下方的小圆点时,也可以实现图片的切换效果,通过for循环及条件语句的使用来制作一款多功能的焦点图轮播效果。实现五张图的轮播
时间: 2024-03-09 12:51:10 浏览: 107
可以使用以下代码实现五张图片的轮播:
HTML代码:
```
<div class="slideshow-container">
<div class="slideshow">
<img src="image1.jpg" alt="Image 1">
<img src="image2.jpg" alt="Image 2">
<img src="image3.jpg" alt="Image 3">
<img src="image4.jpg" alt="Image 4">
<img src="image5.jpg" alt="Image 5">
</div>
<a class="prev">❮</a>
<a class="next">❯</a>
<div class="dots-container">
<span class="dot"></span>
<span class="dot"></span>
<span class="dot"></span>
<span class="dot"></span>
<span class="dot"></span>
</div>
</div>
```
CSS代码:
```
.slideshow-container {
position: relative;
width: 100%;
max-width: 800px;
margin: 0 auto;
}
.slideshow {
display: flex;
overflow: hidden;
}
.slideshow img {
width: 100%;
height: auto;
}
.prev, .next {
position: absolute;
top: 50%;
transform: translateY(-50%);
font-size: 30px;
font-weight: bold;
color: white;
cursor: pointer;
z-index: 1;
}
.prev {
left: 0;
}
.next {
right: 0;
}
.dots-container {
display: flex;
justify-content: center;
margin-top: 10px;
}
.dot {
width: 10px;
height: 10px;
margin: 0 5px;
border-radius: 50%;
background-color: gray;
cursor: pointer;
}
.active-dot {
background-color: white;
}
```
JavaScript代码:
```
var slideshow = document.querySelector('.slideshow');
var prev = document.querySelector('.prev');
var next = document.querySelector('.next');
var dots = document.querySelectorAll('.dot');
var index = 0;
var timer;
function showSlide(n) {
if (n < 0) {
index = slideshow.children.length - 1;
} else if (n >= slideshow.children.length) {
index = 0;
} else {
index = n;
}
slideshow.style.transform = 'translateX(-' + index + '00%)';
for (var i = 0; i < dots.length; i++) {
dots[i].classList.remove('active-dot');
}
dots[index].classList.add('active-dot');
}
function autoSlide() {
timer = setInterval(function() {
showSlide(index + 1);
}, 3000);
}
prev.addEventListener('click', function() {
clearInterval(timer);
showSlide(index - 1);
autoSlide();
});
next.addEventListener('click', function() {
clearInterval(timer);
showSlide(index + 1);
autoSlide();
});
for (var i = 0; i < dots.length; i++) {
dots[i].addEventListener('click', function() {
clearInterval(timer);
showSlide(Array.prototype.indexOf.call(dots, this));
autoSlide();
});
}
autoSlide();
```
注释:
- `slideshow`: 轮播图容器
- `prev`, `next`: 左右箭头
- `dots`: 小圆点容器
- `index`: 当前显示图片的索引
- `timer`: 自动轮播的计时器
`showSlide`函数用于显示指定索引的图片,同时更新小圆点的选中状态。`autoSlide`函数用于自动轮播,每隔3秒切换到下一张图片。点击左右箭头或小圆点时,先清除自动轮播的计时器,然后调用`showSlide`函数切换到指定图片,最后重新启动自动轮播计时器。最后调用`autoSlide`函数启动自动轮播。
阅读全文