1. 程式人生 > >html中使用JS實現圖片輪播效果

html中使用JS實現圖片輪播效果

HTML 部分

  <div id="bannner" class="main_center_bannar">
                                  
                                   <img  src="images/ad-01.jpg"/>
                                   <img  src="images/ad-02.jpg"  style="display:none" />
                                   <img  src="images/ad-03.jpg"  style="display:none" />
                                   <img  src="images/ad-04.jpg"  style="display:none" />
                                   <ul id="ulli"> <li class="selected">1</li><li class="selected">2</li><li class="selected">3</li><li class="selected">4</li> </ul>
 </div>

css

.main_center_bannar {
    width:100%;
   
    position: relative;
}
    .main_center_bannar img {
      
        width: 100%;
    }
    .main_center_bannar ul {
        list-style: none;
        display: flex;
       
        position: absolute;
        left:130px;
        bottom: 10px;
        z-index: 2;
    }

js部分

 var bannner = document.getElementById("bannner");
            var pic = bannner.getElementsByTagName("img");
            var dot = document.getElementById("ulli").getElementsByTagName("li");
           
            var index = 0;
            var timer = null;
            /*定義圖片切換函式*/
            function changePic(curIndex) {
                for (var i = 0; i < pic.length; ++i) {
                    pic[i].style.display = "none";
                  
                }
                pic[curIndex].style.display = "block";
              
            }
            /*index超出圖片總量時歸零*/
            function autoPlay() {
                if (+index >= pic.length) {
                    index = 0;
                }
                changePic(index);
                index++;
            }
            /*定義並呼叫自動播放函式*/
            timer = setInterval(autoPlay, 1500);
            /*滑鼠劃過整個容器時停止自動播放*/
            bannner.onmouseover = function () {
                clearInterval(timer);
            }
            /*滑鼠離開整個容器時繼續播放下一張*/
            bannner.onmouseout = function () {
                timer = setInterval(autoPlay, 1500);
            }
            /*遍歷所有數字導航實現劃過切換至對應的圖片*/
            for (var i = 0; i < dot.length; i++) {
                dot[i].onmouseover = function () {
                    clearInterval(timer);
                    index = this.innerText - 1;
                    changePic(index)
                }
            }