图片轮播

代码

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        ul,
        ul li {
            list-style: none;
        }

        #box {
            width: 600px;
            height: 375px;
            /* border: 10px solid #acacac; */
            margin: 50px auto;
            position: relative;
            overflow:hidden;
        }

        #list {
            width: 3000px;
            height: 375px;
            display: flex;
            position: absolute;
            left: 0;
            top: 0;
        }

        #list li {
            width: 600px;
            height: 375px;
        }

        #list li img {
            width: 100%;
            height: 100%;
        }
    </style>
</head>

<body>
    <div id="box">
        <ul id="list">
            <li><img src="images/a.jpg" alt=""></li>
            <li><img src="images/b.jpg" alt=""></li>
            <li><img src="images/c.jpg" alt=""></li>
            <li><img src="images/d.jpg" alt=""></li>
            <li><img src="images/a.jpg" alt=""></li>
        </ul>
    </div>

    <script>
        var list = document.getElementById('list');
        var lis = list.getElementsByTagName('li');
        var timer = null;
        var timer1 = null;
        var num = 0;
        timer1 = setInterval(function(){
            num++;
            
            if(num > 4){  
                list.style.left = '0px';
                num = 1;
            }

            run(list, 'left', 10, -600*num);
            console.log( list.style.left )
        },5000)



        function run(ele, attr, step, target) {
            step = target > parseInt(getStyle(ele, attr)) ? step : -step;

            clearInterval(timer);
            timer = setInterval(function () {
                var dis = parseInt(getStyle(ele, attr)) + step;
                if (dis <= target && step < 0 || dis >= target && step > 0) {
                    dis = target;
                    clearInterval(timer);
                }
                ele.style[attr] = dis + 'px';
            }, 50)
        }


        // 获取元素样式
        function getStyle(ele, attr) {
            if (window.getComputedStyle) {
                return getComputedStyle(ele)[attr];
            } else {
                return ele.currentStyle[attr];
            }
        }
    </script>
</body>

</html>

 

效果

posted @ 2020-07-09 20:48  石海莹  阅读(173)  评论(0编辑  收藏  举报