赞
踩
以下是基于HTML和JavaScript实现上下轮播和左右轮播的代码和说明文档
HTML代码:
<!DOCTYPE html>
<html>
<head>
<title>轮播图</title>
<style>
.slideshow-container {
position: relative;
width: 500px;
height: 300px;
margin: 0 auto;
overflow: hidden;
}
.slide {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: 0;
transition: opacity 1s ease;
}
.slide.active {
opacity: 1;
}
.dot-container {
text-align: center;
margin-top: 10px;
}
.dot {
display: inline-block;
width: 10px;
height: 10px;
border-radius: 50%;
background-color: gray;
margin: 0 5px;
cursor: pointer;
}
.dot.active {
background-color: black;
}
</style>
</head>
<body>
<div class="slideshow-container">
<div class="slide active">
<img src="image1.jpg" alt="Image 1">
</div>
<div class="slide">
<img src="image2.jpg" alt="Image 2">
</div>
<div class="slide">
<img src="image3.jpg" alt="Image 3">
</div>
</div>
<div class="dot-container">
<span class="dot active"></span>
<span class="dot"></span>
<span class="dot"></span>
</div>
<script src="script.js"></script>
</body>
</html>
JavaScript代码(script.js):
document.addEventListener("DOMContentLoaded", function() {
var slides = document.querySelectorAll(".slide");
var dots = document.querySelectorAll(".dot");
var currentSlide = 0;
var slideInterval = setInterval(nextSlide, 2000);
function nextSlide() {
slides[currentSlide].classList.remove("active");
dots[currentSlide].classList.remove("active");
currentSlide = (currentSlide + 1) % slides.length;
slides[currentSlide].classList.add("active");
dots[currentSlide].classList.add("active");
}
dots.forEach(function(dot, index) {
dot.addEventListener("click", function() {
slides[currentSlide].classList.remove("active");
dots[currentSlide].classList.remove("active");
currentSlide = index;
slides[currentSlide].classList.add("active");
dots[currentSlide].classList.add("active");
});
});
});
说明文档:
.dot-container
)来放置小圆点。.dot
)。document.querySelectorAll
方法选择所有的小圆点,并将它们存储在dots
变量中。dots.forEach
方法遍历所有小圆点,并为每个小圆点添加点击事件监听器。active
类,然后将当前轮播图项和小圆点的索引更新为点击的小圆点的索引,最后将更新后的轮播图项和小圆点添加active
类,以实现切换到对应的轮播图项。nextSlide
函数中,我们也更新了小圆点的active
类,以保持与当前显示的轮播图项对应的小圆点的激活状态。通过以上修改,你现在可以通过点击小圆点来切换轮播图了。每个小圆点代表一个轮播图项,点击不同的小圆点将切换到对应的轮播图项。切换过程中,小圆点的激活状态也会相应地更新。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。