2

实现一个非无限循环不自动切换的轮播图
只需要几张图片和两个按钮(简化)

HTML部分

两个按钮,几张图片(假如有四张图)

 <span id='s1'>右侧按钮</span>
 <ul id='ul'>
     <li class='active'><img src="img/1.png" alt=""></li>
     <li><img src="img/2.png" alt=""></li>
     <li><img src="img/3.png" alt=""></li>
     <li><img src="img/4.png" alt=""></li>
 </ul>  
 <span id='s2'>左侧按钮</span>

CSS部分

动态添加删除liclass属性(native)

    span{ cursor: pointer; }
    #s1,#s2{
        position: absolute;
        top: 130px;
    }
    #s1{ right: 0;}
    #s2{ left:0; }
    ul{
        width: 460px; 
        height: 280px;
        margin: auto;
        overflow: hidden;
        }
    li{
        float: left;
        display: none;
        background-color: orange;
    }
    .active{
        background-color: #dddddd;
        display: block;
    }

JS部分

         window.onload=function(){
            var index = 0,
                imgs =  document.getElementsByTagName("li");
            s1.onclick = function(e){
               index++;
               if(index >= imgs.length){
                    imgs[imgs.length-1].setAttribute("class", "active");
                    alert("已是最后一张图")
                    return index = imgs.length-1;;
                }else{
                    imgs[index-1].removeAttribute("class");
                    imgs[index].setAttribute("class", "active");
                    return index;
                }
            }
            
            s2.onclick=function(){
                if(index>0){
                    imgs[index].removeAttribute("class");
                    imgs[index-1].setAttribute("class", "active");
                    index--;
                    return index-1;
                }else{
                    imgs[0].setAttribute("class", "active");
                    alert("这是第一张图")
                    return index = 0;
                }
            }
        }

Dong
57 声望1 粉丝