下面是一个简单的 HTML 图片轮播(carousel)代码示例,使用纯 HTML 和 CSS 实现,没有依赖任何库(如 jQuery)。
✅ HTML + CSS 图片轮播代码
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>图片轮播</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
background: #f0f0f0;
}
.carousel {
position: relative;
width: 600px;
height: 400px;
margin: 0 auto;
overflow: hidden;
}
.carousel img {
width: 100%;
height: 100%;
display: none;
}
.carousel img.active {
display: block;
}
.carousel-controls {
position: absolute;
top: 20px;
left: 50%;
transform: translateX(-50%);
display: flex;
gap: 10px;
justify-content: center;
}
.carousel-controls button {
background: none;
border: none;
font-size: 24px;
cursor: pointer;
}
.carousel-controls button:hover {
color: #007bff;
}
</style>
</head>
<body>
<div id="carousel">
<img src="image1.jpg" >
<img src="image2.jpg" >
<img src="image3.jpg" >
</div>
<div >
<button onclick="prevImage()">❮</button>
<button onclick="nextImage()">❯</button>
</div>
<script>
const carousel = document.getElementById('carousel');
const images = carousel.querySelectorAll('img');
let currentIndex = 0;
function showImage(index) {
images.forEach((img, i) => {
img.classList.remove('active');
if (i === index) img.classList.add('active');
});
}
function nextImage() {
currentIndex = (currentIndex + 1) % images.length;
showImage(currentIndex);
}
function prevImage() {
currentIndex = (currentIndex - 1 + images.length) % images.length;
showImage(currentIndex);
}
// 初始显示第一个图片
showImage(0);
</script>
</body>
</html>