用js写一个简单的轮播图
时间: 2024-05-31 08:09:11 浏览: 90
好的,以下是一个简单的 JavaScript 轮播图代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>JavaScript 轮播图</title>
<style>
#slider {
width: 500px;
height: 300px;
overflow: hidden;
position: relative;
}
#slider ul {
list-style: none;
margin: 0;
padding: 0;
width: 500px;
height: 300px;
position: relative;
}
#slider ul li {
width: 500px;
height: 300px;
float: left;
}
#slider .btn {
position: absolute;
top: 50%;
transform: translateY(-50%);
z-index: 999;
cursor: pointer;
border-radius: 50%;
width: 30px;
height: 30px;
background-color: #333;
color: #fff;
text-align: center;
line-height: 30px;
font-size: 20px;
}
#slider .btn.prev {
left: 20px;
}
#slider .btn.next {
right: 20px;
}
</style>
</head>
<body>
<div id="slider">
<ul>
<li><img src="https://via.placeholder.com/500x300.png?text=Slide+1" alt="Slide 1"></li>
<li><img src="https://via.placeholder.com/500x300.png?text=Slide+2" alt="Slide 2"></li>
<li><img src="https://via.placeholder.com/500x300.png?text=Slide+3" alt="Slide 3"></li>
<li><img src="https://via.placeholder.com/500x300.png?text=Slide+4" alt="Slide 4"></li>
<li><img src="https://via.placeholder.com/500x300.png?text=Slide+5" alt="Slide 5"></li>
</ul>
<div class="btn prev">❮</div>
<div class="btn next">❯</div>
</div>
<script>
var slider = document.querySelector("#slider");
var sliderUl = slider.querySelector("ul");
var sliderLi = slider.querySelectorAll("li");
var prevBtn = slider.querySelector(".prev");
var nextBtn = slider.querySelector(".next");
var currentIndex = 0;
var intervalId;
function goToSlide(index) {
sliderUl.style.transform = "translateX(-" + index * 500 + "px)";
currentIndex = index;
}
function goToNextSlide() {
if (currentIndex === sliderLi.length - 1) {
goToSlide(0);
} else {
goToSlide(currentIndex + 1);
}
}
function goToPrevSlide() {
if (currentIndex === 0) {
goToSlide(sliderLi.length - 1);
} else {
goToSlide(currentIndex - 1);
}
}
function startAutoPlay() {
intervalId = setInterval(goToNextSlide, 3000);
}
function stopAutoPlay() {
clearInterval(intervalId);
}
prevBtn.addEventListener("click", function () {
goToPrevSlide();
stopAutoPlay();
startAutoPlay();
});
nextBtn.addEventListener("click", function () {
goToNextSlide();
stopAutoPlay();
startAutoPlay();
});
startAutoPlay();
</script>
</body>
</html>
```
在这个示例中,我们使用了一个 `ul` 元素来包含轮播图中的每个幻灯片,每个幻灯片都是一个 `li` 元素,其中包含一个图像。使用 CSS 将 `ul` 元素转换为滚动容器。通过 JavaScript 来实现轮播图的自动播放和手动控制。我们使用了两个按钮,一个是向左箭头,另一个是向右箭头,用于切换幻灯片。我们使用了 `setInterval()` 函数来自动播放幻灯片,并使用 `clearInterval()` 函数停止自动播放。
阅读全文