用js写一个轮播图,手动翻页加自动翻页
时间: 2024-03-25 22:39:14 浏览: 66
利用js来实现轮播图
好的,以下是一个简单的用 JavaScript 实现手动翻页和自动翻页的轮播图:
HTML 代码:
```html
<div class="slider">
<div class="slides">
<img src="image1.jpg">
<img src="image2.jpg">
<img src="image3.jpg">
</div>
<button class="prev">Prev</button>
<button class="next">Next</button>
</div>
```
CSS 代码:
```css
.slider {
position: relative;
}
.slides {
display: flex;
}
.slides img {
width: 100%;
height: auto;
}
.prev,
.next {
position: absolute;
top: 50%;
transform: translateY(-50%);
padding: 10px;
font-size: 20px;
background: transparent;
border: none;
cursor: pointer;
}
.prev {
left: 0;
}
.next {
right: 0;
}
```
JavaScript 代码:
```js
const slider = document.querySelector('.slider');
const slides = slider.querySelector('.slides');
const prevBtn = slider.querySelector('.prev');
const nextBtn = slider.querySelector('.next');
const slideWidth = slides.firstElementChild.clientWidth;
let currentSlide = 0;
let interval;
function goToSlide(index) {
slides.style.transform = `translateX(-${index * slideWidth}px)`;
currentSlide = index;
}
function prevSlide() {
if (currentSlide === 0) {
goToSlide(slides.children.length - 1);
} else {
goToSlide(currentSlide - 1);
}
}
function nextSlide() {
if (currentSlide === slides.children.length - 1) {
goToSlide(0);
} else {
goToSlide(currentSlide + 1);
}
}
prevBtn.addEventListener('click', prevSlide);
nextBtn.addEventListener('click', nextSlide);
function startInterval() {
interval = setInterval(nextSlide, 3000);
}
function stopInterval() {
clearInterval(interval);
}
startInterval();
slider.addEventListener('mouseover', stopInterval);
slider.addEventListener('mouseout', startInterval);
```
这个轮播图有三张图片,通过 `goToSlide(index)` 函数来切换图片,其中 `index` 是图片的索引,从 0 开始。手动翻页通过点击左右箭头来实现,自动翻页使用 `setInterval` 函数来实现,鼠标悬停时停止自动翻页。
阅读全文