在JavaScript中实现div
定时轮播图片的功能,主要涉及以下几个基础概念:
setInterval
或setTimeout
函数来设置定时任务。div
容器。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Carousel</title>
<link rel="stylesheet" href="styles.css">
</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>
<script src="script.js"></script>
</body>
</html>
#carousel {
width: 300px;
height: 200px;
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;
}
const images = document.querySelectorAll('#carousel img');
let currentIndex = 0;
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);
}
setInterval(nextImage, 3000); // Change image every 3 seconds
requestAnimationFrame
来优化动画效果,确保定时器的稳定性。通过以上步骤和代码示例,你可以实现一个简单的定时轮播图片功能,并根据具体需求进行相应的优化和调整。
领取专属 10元无门槛券
手把手带您无忧上云