js自动播放【轮播图】
demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Auto Carousel</title>
<style>
#carousel-container {
width: 300px;
overflow: hidden;
}
#image-list {
display: flex;
transition: transform 0.5s ease-in-out;
}
.carousel-image {
width: 300px;
height: 200px;
object-fit: cover;
}
</style>
</head>
<body>
<div id="carousel-container">
<div id="image-list">
<img class="carousel-image" src="../bg2.jpg" alt="Image 1">
<img class="carousel-image" src="../bg2.jpg" alt="Image 2">
<img class="carousel-image" src="../bg2.jpg" alt="Image 3">
<!-- Add more images as needed -->
</div>
</div>
<script>
const imageList = document.getElementById('image-list');
let currentIndex = 0;
let direction = 1; // 1 for forward, -1 for backward
function updateCarousel() {
const transformValue = -currentIndex * 300; // 300 is the width of each image
imageList.style.transform = `translateX(${transformValue}px)`;
}
function nextSlide() {
currentIndex += direction;
// 检查我们是否到达终点并相应地改变方向
if (currentIndex === imageList.children.length - 1 || currentIndex === 0) {
direction *= -1;
}
updateCarousel();
}
// 设置定时器,每隔一定时间切换到下一张图片
const intervalId = setInterval(nextSlide, 2000); // 切换间隔为2秒
// 如果需要停止轮播,可以使用 clearInterval(intervalId);
// 可选:在鼠标悬停时停止轮播
imageList.addEventListener('mouseenter', () => clearInterval(intervalId));
imageList.addEventListener('mouseleave', () => {
clearInterval(intervalId);
intervalId = setInterval(nextSlide, 2000);
});
</script>
</body>
</html>
本文来自博客园,作者:__username,转载请注明原文链接:https://www.cnblogs.com/code3/p/17875363.html