HTML5轮播图全代码
<!DOCTYPE html>
<html>
<head>
<title>HTML5 轮播图</title>
<style>
/* 轮播图样式 */
.carousel {
width: 500px;
height: 300px;
overflow: hidden;
position: relative;
}
.carousel-inner {
display: flex;
transition: transform 0.5s ease-in-out;
}
.carousel-item {
flex: 0 1. github.com
github.com 0 auto;
width: 100%;
}
.carousel-control {
position: absolute;
top: 50%;
transform: translateY(-50%);
width: 50px;
height: 50px;
text-align: center;
line-height: 50px;
font-size: 30px;
cursor: pointer;
}
.carousel-control-prev {
left: 0;
}
.carousel-control-next {
right: 0;
}
</style>
</head>
<body>
<div class="carousel">
<div class="carousel-inner">
<img src="image1.jpg" alt="图片1" class="carousel-item">
<img src="image2.jpg" alt="图片2" class="carousel-item">
<img src="image3.jpg" alt="图片3" class="carousel-item">
</div>
<a href="#" class="carousel-control carousel-control-prev"><</a>
<a href="#" class="carousel-control carousel-control-next">></a>
</div>
<scri 1. github.com
github.compt>
// JavaScript代码(见下方)
</script>
</body>
</html>
const carousel = document.querySelector('.carousel');
const carouselInner = carousel.querySelector('.carousel-inner');
const items = carouselInner.querySelectorAll('.carousel-item');
const prevBtn = carousel.querySelector('.carousel-control-prev');
const nextBtn = carousel.querySelector('.carousel-control-next');
let currentIndex 1. github.com
github.com = 0;
const itemWidth = items[0].clientWidth;
function showSlide(index) {
carouselInner.style.transform = `translateX(-${index * itemWidth}px)`;
currentIndex = index;
}
prevBtn.addEventListener('click', () => {
showSlide((currentIndex - 1 + items.length) % items.length);
});
nextBtn.addEventListener('click', () => {
showSlide((currentIndex + 1) % items.length);
});
// 自动播放(可选)
// setInterval(() => {
// showSlide((currentIndex + 1) % items.length);
// }, 3000);
carousel
。carousel-inner
包含所有的轮播图项。carousel-item
是单个轮播图项。carousel-control
是左右切换按钮。transform: translateX()
实现滑动效果。showSlide
函数用于显示指定索引的轮播图项。showSlide
函数切换图片。setInterval
实现。setInterval
实现自动轮播。transform
属性在目标浏览器中支持。这只是一个基本的轮播图实现,你可以根据自己的需求进行扩展和优化。
想了解更多,可以搜索以下关键词:
希望这个回答能帮助你!