请用HTML CSS JS 写一个轮播图
时间: 2024-03-29 15:11:11 浏览: 152
好的,下面是一个基本的轮播图实现:
HTML 代码:
```
<div class="slider">
<div class="slides">
<img src="https://via.placeholder.com/600x400?text=Slide+1" alt="Slide 1">
<img src="https://via.placeholder.com/600x400?text=Slide+2" alt="Slide 2">
<img src="https://via.placeholder.com/600x400?text=Slide+3" alt="Slide 3">
</div>
<div class="nav">
<button class="prev">❮</button>
<button class="next">❯</button>
</div>
</div>
```
CSS 代码:
```
.slider {
position: relative;
width: 100%;
height: 400px;
overflow: hidden;
}
.slides {
display: flex;
width: 300%;
height: 100%;
transition: transform 0.5s ease-in-out;
}
.slides img {
width: 33.333%;
height: 100%;
}
.nav {
position: absolute;
top: 50%;
transform: translateY(-50%);
width: 100%;
height: 30px;
display: flex;
justify-content: space-between;
}
.prev,
.next {
width: 30px;
height: 30px;
border: none;
background-color: transparent;
color: #fff;
font-size: 24px;
cursor: pointer;
}
.prev:hover,
.next:hover {
background-color: rgba(255, 255, 255, 0.2);
}
```
JavaScript 代码:
```
const slides = document.querySelector(".slides");
const prevBtn = document.querySelector(".prev");
const nextBtn = document.querySelector(".next");
let counter = 1;
const size = slides.children[0].clientWidth;
slides.style.transform = "translateX(" + (-size * counter) + "px)";
nextBtn.addEventListener("click", () => {
if (counter >= slides.children.length - 1) return;
slides.style.transition = "transform 0.5s ease-in-out";
counter++;
slides.style.transform = "translateX(" + (-size * counter) + "px)";
});
prevBtn.addEventListener("click", () => {
if (counter <= 0) return;
slides.style.transition = "transform 0.5s ease-in-out";
counter--;
slides.style.transform = "translateX(" + (-size * counter) + "px)";
});
slides.addEventListener("transitionend", () => {
if (slides.children[counter].id === "lastClone") {
slides.style.transition = "none";
counter = slides.children.length - 2;
slides.style.transform = "translateX(" + (-size * counter) + "px)";
}
if (slides.children[counter].id === "firstClone") {
slides.style.transition = "none";
counter = slides.children.length - counter;
slides.style.transform = "translateX(" + (-size * counter) + "px)";
}
});
```
这个轮播图会在用户点击“上一个”和“下一个”按钮时切换图片,也会自动循环轮播。可以根据需要进行修改和扩展。
阅读全文