自动切换播放轮播图

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style type="text/css">
            *{
                margin: 0;
                padding: 0;
            }
            #box{
                position: relative;
                margin: 100px auto;
                width: 300px;
            }
            li{
                list-style: none;
            }
            ul li{
                position: absolute;
                left: 0;
                top: 0;
            }
            ol li{
                
                width: 20px;
                height: 20px;
                background: yellow;
                border-radius: 50%;
                float: left;
                text-align: center;
                line-height: 20px;
                margin-right: 3px;
            }
            ol{
                position: absolute;
                right: 32px;
                bottom: -180px;
                z-index: 99999;
            }
            .red{
                background: red;
            }
        </style>
    </head>
    <body>
        <div id="box">
            <ul id="up">
                <li style="z-index: 1;"><img src="a.jpg" alt="" /></li>
                <li><img src="b.jpg" alt="" /></li>
                <li><img src="c.jpg" alt="" /></li>
                <li><img src="d.jpg" alt="" /></li>
            </ul>
            <ol id="down">
                <li class="red">1</li>
                <li>2</li>
                <li>3</li>
                <li>4</li>
            </ol>
        </div>
    </body>
</html>
<script type="text/javascript">
    var index = 0;//控制下标和图片对应关系
    var timer = null;
    var olist = document.getElementById("down").children;
    var ulist = document.getElementById("up").children;
    timer = setInterval( autoPlay,1500 );
    function autoPlay(){
        index++;
        //排他思想 将所有文字样式清除 所有图片隐藏
        for( var i = 0 ; i < olist.length ; i++ ){
            olist[i].className = "";
            ulist[i].style.display = "none";
        }
        //判断index越界问题
        if( index == olist.length ){
            index = 0;
        }
        //控制index对应的图片和文字对应显示
        olist[index].className = "red";
        ulist[index].style.display = "block";
    }
    //鼠标移入移出到olist上 操作定时器的停止和启动
    for( let i = 0 ; i <olist.length ; i++ ){
        olist[i].onmouseover = function(){
            clearInterval( timer );
            //获取鼠标当前移入到li上的下标
            index = i-1;
            autoPlay();
        }
        olist[i].onmouseout = function(){
            timer = setInterval( autoPlay,1500 );
        }
    }
</script>

猜你喜欢

转载自www.cnblogs.com/tis100204/p/10328841.html