简单实现轮播图效果

2020-05-01
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        #box {
            width: 300px;
            height: 300px;
            border: 1px solid red;
            position: relative;
            margin: 50px auto;
        }

        ul {
            list-style-type: none;
        }

        ul li {
            display: inline-block;
            position: absolute;
            top: 0;
            left: 0;
        }

        ul li div {
            border: 1px solid #dadada;
            width: 300px;
            height: 300px;
        }

        ul li .div1 {
            background-color: blue;
        }

        ul li .div2 {
            background-color: black;
            display: none;
        }

        ul li .div3 {
            background-color: red;
            display: none;
        }
    </style>
</head>
<body>
<div id="box">
    <ul>
        <li>
            <div class="div1"></div>
        </li>
        <li>
            <div class="div2"></div>
        </li>
        <li>
            <div class="div3"></div>
        </li>
    </ul>
    <script>
        // 当前显示的第几个
        let current = 0;
        let divObjs = document.getElementById("box").getElementsByTagName('div');
        setInterval(function () {
            current++;
            if (current > 2) {
                current = 0;
            }
            for (let i = 0; i < divObjs.length; i++) {
                divObjs[i].style.display = 'none';
            }
            divObjs[current].style.display = 'block';
        }, 1500);
    </script>
</div>
</body>
</html>