<!DOCTYPE html>
<html>
<head>
<title>轮播图</title>
<style>
/* 设置轮播图容器的宽度和高度 */
.container {
width: 1000px;
height: 400px;
overflow: hidden;
position: relative;
margin: 0 auto;
}
/* 设置轮播图中每张图片的样式 */
.container img {
width: 1000px;
height: 400px;
position: absolute;
top: 0;
left: 0;
opacity: 0;
transition: opacity 1s ease-in-out;
}
/* 设置轮播图中第一张图片的样式 */
.container img:first-child {
opacity: 1;
}
/* 设置轮播图中的圆点容器的样式 */
.dots {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
display: flex;
}
/* 设置轮播图中每个圆点的样式 */
.dot {
width: 10px;
height: 10px;
border-radius: 50%;
background-color: #fff;
margin-right: 10px;
cursor: pointer;
}
/* 设置轮播图中当前圆点的样式 */
.dot.active {
background-color: #000;
}
</style>
</head>
<body>
<div class="container">
<img src="image1.jpg">
<img src="image2.jpg">
<img src="image3.jpg">
<div class="dots">
<div class="dot active"></div>
<div class="dot"></div>
<div class="dot"></div>
</div>
</div>
<script>
// 获取轮播图容器和圆点容器
var container = document.querySelector('.container');
var dots = document.querySelector('.dots');
// 获取轮播图中的所有图片和圆点
var images = container.querySelectorAll('img');
var dotsArray = Array.from(dots.children);
// 设置当前显示的图片和圆点的索引
var currentIndex = 0;
// 定义轮播函数
function carousel() {
// 隐藏当前显示的图片和圆点
images[currentIndex].style.opacity = 0;
dotsArray[currentIndex].classList.remove('active');
// 计算下一张图片和圆点的索引
currentIndex = (currentIndex + 1) % images.length;
// 显示下一张图片和圆点
images[currentIndex].style.opacity = 1;
dotsArray[currentIndex].classList.add('active');
}
// 设置定时器,每隔3秒钟调用一次轮播函数
setInterval(carousel, 3000);
// 为每个圆点添加点击事件,点击后显示对应的图片
dotsArray.forEach(function(dot, index) {
dot.addEventListener('click', function() {
// 隐藏当前显示的图片和圆点
images[currentIndex].style.opacity = 0;
dotsArray[currentIndex].classList.remove('active');
// 显示点击的圆点对应的图片和圆点
currentIndex = index;
images[currentIndex].style.opacity = 1;
dotsArray[currentIndex].classList.add('active');
});
});
</script>
</body>
</html>
轮播图用js,css,html
于 2023-04-10 15:12:32 首次发布