图片轮播是一种网页设计技术,用于在网页上自动或手动切换显示多张图片。它通常用于展示产品、服务或其他视觉内容,以吸引用户的注意力并提高用户体验。
以下是一个简单的JavaScript实现图片轮播的示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>图片轮播</title>
<style>
#carousel {
width: 600px;
height: 400px;
overflow: hidden;
position: relative;
}
#carousel img {
width: 100%;
height: 100%;
position: absolute;
opacity: 0;
transition: opacity 1s ease-in-out;
}
#carousel img.active {
opacity: 1;
}
</style>
</head>
<body>
<div id="carousel">
<img src="image1.jpg" alt="Image 1" class="active">
<img src="image2.jpg" alt="Image 2">
<img src="image3.jpg" alt="Image 3">
</div>
<button onclick="prevImage()">Prev</button>
<button onclick="nextImage()">Next</button>
<script src="carousel.js"></script>
</body>
</html>
let currentIndex = 0;
const images = document.querySelectorAll('#carousel img');
function showImage(index) {
images.forEach((img, i) => {
img.classList.remove('active');
});
images[index].classList.add('active');
}
function nextImage() {
currentIndex = (currentIndex + 1) % images.length;
showImage(currentIndex);
}
function prevImage() {
currentIndex = (currentIndex - 1 + images.length) % images.length;
showImage(currentIndex);
}
// 自动轮播功能
setInterval(nextImage, 3000); // 每3秒切换一次图片
通过以上步骤和代码示例,你可以实现一个基本的图片轮播功能,并根据需要进行扩展和优化。
领取专属 10元无门槛券
手把手带您无忧上云