JavaScript 图片轮播

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style type="text/css">
            #main{
                width: 300px;
                padding: 20px;
                margin: 10px auto;
                background-color: yellow;
                text-align: center;
            }
        </style>
    </head>
    <body>
        <div id="main">
            <p id="info"></p>
            <img src="img/1.jpg"/>
        </div>
        <button id="start">开始/暂停</button>
    </body>
    
    <script type="text/javascript">
        //创建一个数组来保存图片路径,切换图片就是切换图片路径
        var imgArr=["img/1.jpg","img/2.jpg","img/3.jpg","img/4.jpg"];
        //获取img元素,
        var img=document.getElementsByTagName("img")[0];
        //alert(img);
        //创建保存图片路径的索引(数组下标)
        var index=0;
        
        //-开启定时器来自动切换图片
        var timer;
        var count=0;
        //设置一下开始/暂停
        document.getElementById("start").onclick=function(){
            count++;
            if(count%2!=0){
                timer=setInterval(function(){
                index++;
//                if(index>imgArr.length-1){
//                    index=0;
//                }
                  index=index % imgArr.length;//同上面的if判断 0%4=4 1%4=1 ...4%4=0
                //换图
                img.src=imgArr[index];
                
                },1500);
            }else{
                clearInterval(timer);
            }
            
        }
    </script>
</html>

猜你喜欢

转载自www.cnblogs.com/wangdongwei/p/11304307.html