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>

posted @ 2023-12-04 16:51  __username  阅读(35)  评论(0编辑  收藏  举报

本文作者:DIVMonster

本文链接:https://www.cnblogs.com/guangzan/p/12886111.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。