JS轮播图

window.onload = function(){
    var container = document.getElementById("container");
    var list = document.getElementById("list");
    var next = document.getElementById("next");
    var prev = document.getElementById("prev");
    var btns = document.getElementById("btns").children;
    var index = 0;
    var timer;
    next.onclick = function(){
        if(animated){
            return false;
        }
        animate(-600);
        index++;
        showBtn();
        console.log(index);
        
    }
    prev.onclick = function(){
        if(animated){
            return false;
        }
        animate(600);
        index--;
        showBtn();
    }
    for(let i=0; i-600){
            list.style.left = "-3000px";
        }
    }
    var animated = false;
    function animate(offset){
        let newLeft = parseInt(list.style.left) + offset;  //设定要偏移的距离
        var timer = 300;  //偏移一次总共用时300ms
        var interval = 10;  //偏移一次中分10小次
        var speed = offset / (timer / interval);  //每次偏移的速度 20
        function go(){
            animated = true;  //动画开始
            var leftValue = parseInt(list.style.left);  //目前left的值
            if((speed<0 && leftValue>newLeft) || (speed>0 && leftValue-600){
                    list.style.left = -3000 + "px";
                }else if(newLeft<-3000){
                    list.style.left = -600 + "px";
                }else{
                    list.style.left = newLeft + "px";
                }
            }
        }
        go();
    }
    function showBtn(){
        for(let i=0; i4){
            index = 0;
        }else if(index<0){
            index = 4;
        }
        btns[index].classList.add("current");
    }
    function autoplay(){
        timer = setInterval(function(){
            next.onclick();
        }, 1000);
    }
    function stopplay(){
        clearInterval(timer);
    }
    autoplay();
    container.onmouseover = stopplay;
    container.onmouseout = autoplay;
}

你可能感兴趣的:(JS轮播图)