【JS】轮播图

第一种方法:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>D24C04429</title>
    <style>
        #pic {
            width: 300px;
            height: 240px;
            display: block;
            margin: auto;
        }
    </style>
</head>
<body>
    <img src="./images/1.jpg" id="pic">
    <script>
        var arr = new Array(4);
        arr[0] = "./images/1.jpg";
        arr[1] = "./images/2.jpg";
        arr[2] = "./images/3.jpg";
        arr[3] = "./images/4.jpg";
        var i = 0;
        function change() {
            i++;
            if (i == 4) {
                i = 0;
            }
            document.getElementById("pic").setAttribute("src", arr[i]);
        }
        setInterval(change, 2000);
    </script>
</body>
</html>

第二种方法:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>简单轮播图</title>
    <style>
        .banner {
            width: 600px;
            height: 300px;
            overflow: hidden;
            position: relative;
            margin: 40px auto;
            background: #eee;
        }
        .banner img {
            position: absolute;
            width: 100%;
            height: 100%;
            left: 0;
            top: 0;
            opacity: 0;
            transition: opacity 1s;
        }
        .banner img.active {
            opacity: 1;
            z-index: 2;
        }
    </style>
</head>
<body>
    <div class="banner">
        <img src="img/1.jpg" alt="" class="active">
        <img src="img/2.jpg" alt="">
        <img src="img/3.jpg" alt="">
    </div>
    <script>
        const imgs = document.querySelectorAll('.banner img');
        let idx = 0;
        setInterval(() => {
            imgs[idx].classList.remove('active');
            idx = (idx + 1) % imgs.length;
            imgs[idx].classList.add('active');
        }, 2000);
    </script>
</body>
</html>


打赏
分享给朋友:

相关文章

【H5】ul,li练习6个月前 (12-04)
【JS】删除特定数组3个月前 (03-31)
【JS】冒泡排序3个月前 (03-31)
【JS】加减乘除函数2个月前 (04-07)